javascript - 从 Javascript 发送到 Django Views 的 JSON 对象为空
问题描述
我正在尝试通过 ajax 将一些数据从 Javascript 发送到 Django。这是我的 JS 代码:
var json_name = {'name': 123}
$.ajax({
method: 'POST',
url: 'my url',
contentType: "application/json",
headers: {
'Content-Type':'application/json',
'X-CSRFToken': "{{ csrf_token }}"
},
data: JSON.stringify(json_name),
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
这是我的 Views.py:
def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')
我得到的输出为b''
当我尝试包含这些行时:
data = json.loads(request.body)
print(data)
我收到此错误:
TypeError: the JSON object must be str, not 'bytes'
我从这里拿了一些参考
有人可以帮我弄这个吗?如果您需要任何其他信息来解决此问题,我很乐意分享。
解决方案
在我的头上掉了一半头发后,我通过以下方式解决了它:
视图.py:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def myview(request):
if request.is_ajax():
if request.method == 'POST':
data = request.POST.get('senddata')
print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')
我的 JS 代码:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
$.ajax({
type: 'POST',
url: 'my url',
// contentType: "application/json",
// headers: {
// 'Content-Type':'application/json',
// 'X-CSRFToken': "{{ csrf_token }}"
// },
dataType: "json",
data: {
senddata: JSON.stringify(json_name),
},
// data: json_name,
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
当我运行它时,它会显示,it didnt work
但我可以在终端中看到输出,即数据已通过。
我尝试在 ajax 请求中包含 csrf 令牌,但失败了。因此,我在视图中使用了 csrf_exempt。
这可能是一种肮脏的做事方式,但它现在有效。如果有人有一个整洁和更好的答案,请在此处发布!
推荐阅读
- php - FPDF 生成单个页面而不是一个大页面
- php - Nginx 重写目录并排除子目录
- node.js - 我应该使用 cookie 还是本地存储将数据持久化到前端?
- html - 如何保持文本与其父 div 的宽度相同?
- android - 是否有移动和穿戴应用程序共享存储?
- android - Flutter 版本解决此特定应用程序上的失败错误
- amazon-dynamodb - 如何使用全局二级索引编写获取方法 DynamoDB?
- python - Python:如何在 Sublime 中运行终端来阅读电子邮件?
- continuous-integration - Google Lighthouse CI - LHCI 服务器可用于多个自动运行
- docker - nc host.docker.internal 在容器内无法访问主机 IP 地址