javascript - 如何解决 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')
解决方案
您收到此错误的原因是 JSON 库无法正确编译字符串。您的代码需要更改几件事。删除 request.body() 附近的 'r' 字符。json.loads() 中不需要“read()”函数。您可以将数组预处理为字符串,一旦完成,然后将其传递给 ajax。数据字段将只有字符串。所以 ajax 代码字段应该看起来像
data: new_array
推荐阅读
- ios - SwiftUI:观察@Environment 属性变化
- sql - 如何在 SQL 中从生效日期创建时间序列
- php - CakePHP bin/cake migrations migrate 命令在错误时返回退出代码 0
- javascript - .then() 异步中的 While 循环
- java - 如何仅打印 kafka 记录值而不是所有其他数据?
- c# - 如何保持两个 Winforms 标签居中对齐?
- spring - 如何修复:FaultTolerantChunkProcessor 的 Nullpointer 异常(带有 SCDF 和 docker 的 Spring Batch)?
- c# - NLog 不会在进程退出时刷新所有日志条目
- javascript - NG-bootstrap:通过一键式处理程序在单独的组件中打开多个模式
- python - 使用 import module_name as module_alias 时 sqlalchemy 模块的常用别名