Javascript 如何解决ajax django中的JSONdecode错误?

Javascript 如何解决ajax django中的JSONdecode错误?,javascript,django,ajax,http-post,Javascript,Django,Ajax,Http Post,将POST请求从ajax发送到django views.py时,我收到了JSONdecode错误。POST发送一个json数组。本文中的数据将用于创建模型。谢谢你的提示 错误: Exception Type: JSONDecodeError at /order-confirmation Exception Value: Expecting value: line 1 column 1 (char 0) Request information: USER: ledi12 GET: No GET

将POST请求从ajax发送到django views.py时,我收到了JSONdecode错误。POST发送一个json数组。本文中的数据将用于创建模型。谢谢你的提示

错误:

Exception Type: JSONDecodeError at /order-confirmation
Exception Value: Expecting value: line 1 column 1 (char 0)
Request information:
USER: ledi12

GET: No GET data

POST: No POST data

FILES: No FILES data
AJAX请求:

var new_array = JSON.stringify(array)
      $.ajax({
        url: 'http://localhost:8000/order-confirmation',
        type: 'POST',
        data: '{"array":"' + new_array+'"}',
        processData: false,
        contentType: "application/json",
        dataType: "json",
        headers: {"X-CSRFToken":'{{ csrf_token }}'},
        success: function (result) {
            console.log(result.d);
        },
        error: function (result) {
            console.log(result);
        }
      });
观点:

@csrf_exempt
def order_confirmation(request):

    if request.method == 'POST':
        data = json.loads(r"request.body").read()
        print(data)
        return HttpResponse(status=200) 
    else:
        return render(request, 'main_templates/order_confirmation.html')

出现此错误的原因是JSON库无法正确编译字符串。您的代码需要更改几件事。删除request.body()附近的“r”字符。json.loads()中不需要“read()”函数。您可以将数组预处理为字符串,并在处理完成后将其传递给ajax。数据字段将只包含字符串。因此,ajax代码字段应该如下所示

data: new_array

不要使用字符串操作创建JSON,请使用
data:JSON.stringify({array:array})
r“request.body”
应该是
request.body
@Barmar再次感谢先生:)@胡莎,你明白了吗?