【发布时间】: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