简体   繁体   English

jQuery,AJAX使用JSON发布Javascript数组

[英]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: 我有一个Javascript变量,它是一个数组(我将字符串推入其中),并且我必须通过AJAX jQuery.POST()方法将该列表发送回服务器:

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: 在服务器中,我正在运行Django,并尝试使用以下视图解码POST请求:

@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) ": 我得到“ 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? [“ 42”]是不是只有一个元素的有效JSON数组定义?

I don't know anything about Django, so, this a total guess :D 我对Django一无所知,所以,这完全是猜测: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: 如果我没记错的话,您的request.body看起来像这样:

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) 

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

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