HttpResponse 每次将数据返回给前端需要用 json 模块序列化,且前端也要反序列化:
# views.py
import json
def index(request):
message = '请求成功'
# ret = {'message': '请求成功'}
return HttpResponse(json.dumps(message)) # 序列化
# index.html
$.ajax({
url: '/accounts/ajax/',
type: 'post',
data: {
'p': 123,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
# 反序列化,或使用 json.parse(arg)
dataType: "JSON",
success: function (arg) {
console.log(arg.message);
}
})
JsonResponse 只能序列化字典格式,不能序列化字符串,且前端不用反序列化:
from django.http import JsonResponse def index(request): ret = {'message': '请求成功'} return JsonResponse(ret) # 序列化 # index.html $.ajax({ url: '/accounts/ajax/', type: 'post', data: { 'p': 123, csrfmiddlewaretoken: '{{ csrf_token }}' }, # 不需要反序列化 # dataType: "JSON", success: function (arg) { console.log(arg.message); # 请求成功 } })
以上就是关于“DjangoJSonResponse对象如何实现”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注云服务器网(yuntue.com)行业资讯频道。
本文来源:https://www.yuntue.com/post/47481.html | 云服务器网,转载请注明出处!

微信扫一扫打赏
支付宝扫一扫打赏