如何解决 ajax django 中的 JSONdecode 错误?
How to solve JSONdecode error in ajax django?
从 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 库无法正确编译字符串。您的代码需要更改几处内容。删除 request.body() 附近的 'r' 字符。 json.loads() 中不需要 'read()' 函数。您可以将数组预处理为字符串,完成后将其传递给 ajax。数据字段将只有字符串。所以 ajax 代码字段应该看起来像
data: new_array
从 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 库无法正确编译字符串。您的代码需要更改几处内容。删除 request.body() 附近的 'r' 字符。 json.loads() 中不需要 'read()' 函数。您可以将数组预处理为字符串,完成后将其传递给 ajax。数据字段将只有字符串。所以 ajax 代码字段应该看起来像
data: new_array