原來是contentType為application/json時,Django不支持request.POST.get(),但可以通過request.body來獲取string類型的參數(shù):
data = json.loads(request.body)
data.get('xxx')
注意:這里的json.loads(request.body)可能會因為python版本的原因會報錯,詳細(xì)看https://www.cnblogs.com/hooo-1102/p/12055742.html
舉個栗子:
注冊頁面,前端的ajax請求:
$.ajax({
// 請求方式
type:"post",
// contentType
contentType:"application/json",
// dataType
dataType:"json",
// url
url:"http://127.0.0.1:8000/v1/users",
// 把JS的對象或數(shù)組序列化一個json 字符串
data:JSON.stringify(post_data),
// result 為請求的返回結(jié)果對象
success:function (result) {
if (200 == result.code){
window.localStorage.setItem('dnblog_token', result.data.token)
window.localStorage.setItem('dnblog_user', result.username)
alert("注冊成功 點擊確認(rèn)即可條轉(zhuǎn)到自己博客的主頁")
window.location.href = '/' + result.username + '/topics'
}else{
alert(result.error)
}
}
});
后端:
if request.method == 'POST':
#注冊
json_str = request.body
if not json_str:
result = {'code':202, 'error': 'Please POST data!!'}
return JsonResponse(result)
#如果當(dāng)前報錯,請執(zhí)行 json_str = json_str.decode()
json_obj = json.loads(json_str)
username = json_obj.get('username')
email = json_obj.get('email')
password_1 = json_obj.get('password_1')
password_2 = json_obj.get('password_2')
轉(zhuǎn)載地址:https://www.cnblogs.com/hooo-1102/p/12090527.html