简体   繁体   English

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

[英]Passing data from html to python using ajax

Greeting everyone, I'm trying to pass json data from html to python, Im getting the data but the format is incorrect, 问候大家,我正在尝试将json数据从html传递到python,我正在获取数据,但格式不正确,

Below is my code 下面是我的代码

HTML 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 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 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)

The result I wanted is : 我想要的结果是:

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

but what I'm getting is : 但是我得到的是:

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

How can i remove the extra bracket? 我如何卸下多余的支架? thanks! 谢谢!

I don't know much about python, but you need to ensure that your values aren't stringified using JSON.stringify . 我对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) {
  },
...

Also, jQuery automatically handles encoding of the data. 而且,jQuery自动处理数据的编码。 So, the actual parameters name which is submitted to the server will be stat[] . 因此,提交给服务器的实际参数名称将为stat[]

I think you will need to change the name of parameter to stat[] while retrieving the values on python side. 我认为您在检索python端的值时需要将参数名称更改为stat[] Maybe, in this line: 也许在这一行:

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

For more details about how parameters are being sent, observe this fiddle . 有关如何发送参数的更多详细信息,请观察此小提琴

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

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