【问题标题】:How to solve JSONdecode error in ajax django?如何解决 ajax django 中的 JSONdecode 错误?
【发布时间】:2020-01-16 18:20:29
【问题描述】:

从 ajax 向 django views.py 发送 POST 请求时收到 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')

【问题讨论】:

  • 不要用字符串操作创建JSON,使用data: JSON.stringify({array: array})
  • r"request.body" 应该只是 request.body
  • @Barmar 再次感谢先生! :)

标签: javascript django ajax http-post


【解决方案1】:

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

data: new_array

【讨论】:

  • @husa 你明白了吗?
猜你喜欢
  • 1970-01-01
  • 2020-02-08
  • 2019-09-22
  • 2021-08-04
  • 2021-06-14
  • 2021-11-14
  • 2020-07-22
  • 2018-09-28
  • 2021-03-23
相关资源
最近更新 更多