简体   繁体   中英

jQuery, AJAX post Javascript array with JSON

I have a Javascript variable which is an array (I push strings into it) and I have to send that list back to the server through an AJAX jQuery.POST() method:

var user_list = new Array();
user_list.push("42");
var data = { user_list: JSON.stringify(user_list)};
$.post('/accounts/ajax/user_verification/', data)
    .done( my_cb );

In the server, I am running Django and try to decode the POST request with the following view:

@login_required
def user_verification(request):

    if not request.POST.has_key('user_list'):
        print (__name__ + ', user_verification, raising BadRequest.')
        raise Exception("'user_list' not found as a POST parameter.")

    value = unicode(request.POST['user_list'])
    print (__name__ + ', value, v = ' + value)
    user_list = json.loads(request.body) 

I get the following output and posterior exception thrown by " json.loads(request.body) ":

accounts.ajax, value, v = ["42"]
ValueError: No JSON object could be decoded

Isn't ["42"] a valid JSON array definition with a single element?

I don't know anything about Django, so, this a total guess :D

import json
...
value = json.load(request.POST['user_list'])

I might be completely wrong here, but it seems to me that you are trying to decode a wrong thing. If I'm not mistaken, you request.body looks like this:

user_list=["42"]

and if you try to decode this, you have a problem. So why don't you decode the value from variable value?

user_list = json.loads(value) 

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