urls.py
urlpatterns = [ path('admin/', admin.site.urls), # ajax 相关 path("ajax_json/", views.ajax_json), ]
views.py
def ajax_json(request):
import json
print(1, request.POST)
print(2, request.body)
print(3, request.FILES)
data = json.loads(request.body.decode())
print(data, type(data))
return HttpResponse("ok")
ajax_temp.html
<hr>
<button id="btn4">上传json数据</button>
<hr>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
{#上传json数据#}
$("#btn4").click(function () {
$.ajax({
url: "/ajax_json/",
type: "post",
contentType: "json",
headers: {"X-CSRFToken": $("[name='csrfmiddlewaretoken']").val()}, // 在请求头中添加csrf
data: JSON.stringify({
a:12,
b:23,
user: "alex",
}),
success: function (data) {
console.log(data)
}
})
});
</script>
把数据格式如下:
a:12, b:23, user: "alex",
data = json.loads(request.body.decode())
通过json序列化成字典类型的数据:
{'a': 12, 'b': 23, 'user': 'alex'} <class 'dict'>