原来是contentType为application/json时,Django不支持request.POST.get(),但可以通过request.body来获取string类型的参数:
data = json.loads(request.body) data.get(\'xxx\')
注意:这里的json.loads(request.body)可能会因为python版本的原因会报错,详细看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的对象或数组序列化一个json 字符串 data:JSON.stringify(post_data), // result 为请求的返回结果对象 success:function (result) { if (200 == result.code){ window.localStorage.setItem(\'dnblog_token\', result.data.token) window.localStorage.setItem(\'dnblog_user\', result.username) alert("注册成功 点击确认即可条转到自己博客的主页") 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) #如果当前报错,请执行 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\')