繁体   English   中英

使用Ajax将数据从html传递到python

[英]Passing data from html to python using ajax

问候大家,我正在尝试将json数据从html传递到python,我正在获取数据,但格式不正确,

下面是我的代码

HTML

<select class="js-example-basic-multiple" id="Status" name="Status" multiple="multiple" style="display:inline-block;">
    {% comment %} <option value="ALL" checked="1">ALL</option> {% endcomment %}
    <option value="new">New</option>
    <option value="bid">Bid</option>
    <option value="inprogress">In Progress</option>
    <option value="onhold">On Hold</option>
    <option value="completed">Completed</option>
    <option value="archived">Archived</option>
</select>

JavaScript的

$('#Status').change(function(){
    var selected_status = $('#Status').select2('val');
    var status_text = JSON.stringify(selected_status);
    $.ajax({
            url : '/dashboard/marketing/', // the endpoint
            type : 'GET', // http method
            data : { 'stat' : status_text,
                    'csrfmiddlewaretoken': '{{csrf_token}}'
                }, // data sent with the post request
            // handle a successful response
            success : function(data) {
            },
    });
});

view.py

stat = request.GET.getlist('stat')
    print(stat)
    for selected_status in stat:
        get_project_on_status = Project.objects.all().filter(project_stage=selected_status)
        for project in get_project_on_status:
            project_on_status_list.append(project)

我想要的结果是:

["new","bid","inprogress","onhold","completed"]

但是我得到的是:

['["new","bid","inprogress","onhold","completed"]']

我如何卸下多余的支架? 谢谢!

我对python不太了解,但是您需要确保不使用JSON.stringify对值进行字符串化。

var status_text = selected_status; // Remove JSON.stringify from here

$.ajax({
  url : '/dashboard/marketing/', // the endpoint
  type : 'GET', // http method
  data : { 'stat' : status_text,
           'csrfmiddlewaretoken': '{{csrf_token}}'
         }, // data sent with the post request
  // handle a successful response
  success : function(data) {
  },
...

而且,jQuery自动处理数据的编码。 因此,提交给服务器的实际参数名称将为stat[]

我认为您在检索python端的值时需要将参数名称更改为stat[] 也许在这一行:

stat = request.GET.getlist('stat[]')

有关如何发送参数的更多详细信息,请观察此小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM