简体   繁体   中英

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,

Below is my code

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)

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 .

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. So, the actual parameters name which is submitted to the server will be stat[] .

I think you will need to change the name of parameter to stat[] while retrieving the values on python side. Maybe, in this line:

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

For more details about how parameters are being sent, observe this fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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