首页 > 解决方案 > 如何解决 ajax django 中的 JSONdecode 错误?

问题描述

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

错误:

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

标签: javascriptdjangoajaxhttp-post

解决方案


您收到此错误的原因是 JSON 库无法正确编译字符串。您的代码需要更改几件事。删除 request.body() 附近的 'r' 字符。json.loads() 中不需要“read()”函数。您可以将数组预处理为字符串,一旦完成,然后将其传递给 ajax。数据字段将只有字符串。所以 ajax 代码字段应该看起来像

data: new_array

推荐阅读