【问题标题】:how to send data to server with select tag without form如何在没有表单的情况下使用选择标签将数据发送到服务器
【发布时间】:2026-02-21 14:15:02
【问题描述】:

我的 html 文件中有一个选择标记。我希望当用户更改他/她的选择时,我必须使用 ajax 的页面将用户选择的值发送到我的 views.py 函数,然后我用这个值重新创建页面。 我的html代码:

<div id="response>
    <select name="page_length_name" id="page_length_id">
        <option id="opt1">10</option>
        <option id="opt2">20</option>
        <option id="opt3">30</option>
        <option id="opt4">40</option>
    </select>
     //here is a table
</div>

(此选择标签不在表单中)。我希望它被修复,直到用户更改数据。所以我想我必须使用cookie。我不知道我可以使用这样的功能,虽然选择不是形式?它应该是“POST”方法吗? post只能在表格中使用吗?如果是,那么我如何将数据(我的选择标签)发送到服务器?

$(function() {
                $('#page_length_id').change(function() {
                temp = ["page_length_id"].options[selectedIndex].value;
                $.ajax({
                    type: "POST",
                    data: temp,
                    url: 'backup/',
                    success: function(data) {
                        alert("success");
                        $("#response").html(data);
                    }
                });
            })

还有我怎样才能强制这个选择值在 cookie 中?只用views.py中的这行代码就够了吗?:

table_length = request.COOKIES.get('table_length')

这是我的 viwes.py:

def backup(request):
    if request.is_ajax():
        try:
            table_length = request.COOKIES.get('table_length')
        except Exception:
            table_length = 10
        if not page_length:
            table_length = 10 
        //here i create the page with xsl and send it to a page to be shown 
        result = style.applyStylesheet(doc)
        out = style.saveResultToString( result )
        ok =  mark_safe(out)
        style.freeStylesheet()
        doc.freeDoc()
        result.freeDoc()
        if request.method == 'POST': 
            return HttpResponse(ok)
        else:
            return render_to_response("show.html", {
                'str': ok,
                }, context_instance=RequestContext(request))

谢谢。

【问题讨论】:

  • 问题太多。请说明您遇到的问题。你的方法会引发错误吗?另外,您是否使用 csrf 正确设置了 ajax 请求:docs
  • 首先:我想知道如何将用户选择发送到服务器? (我没有表单,所以我想知道我可以使用 "$.ajax({type: "POST"..." 吗?我可以在没有任何表单的情况下使用 post 方法吗?)
  • 当用户更改选择标签中的选项时没有任何反应。嗯...在我的另一个与 ajax 一起使用的视图函数中,我没有 csrf 并且它可以工作。

标签: html django jquery


【解决方案1】:

对于ajax问题,可以很方便的使用

  $.ajax({
    type:"POT",
    url :....,
    data:{
        .......
        'csrfmiddlewaretoken': $("{% csrf_token %}").find("input").attr("value"),
    },    
    dataType:"html",
    error:function(data){},
    success:function(data){
      ....
    },
  });

但你需要放

<input type="hidden" id="csrf_token" value="{{csrf_token}}"/> 

在你的 html 中

如果你用表单发送数据,你也应该使用 csrf

<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

https://docs.djangoproject.com/en/dev/topics/forms/

【讨论】:

  • 非常感谢。当我想发送表单数据(使用 post 方法)时,我也应该使用 csrf 吗?
  • 是的,你也应该使用 csrf
    {% csrf_token %} {{ form.as_p }}
    docs.djangoproject.com/en/dev/topics/forms
最近更新 更多