Django Rest Framework 版本(下)
在前端向后端发送 form 表单或者 ajax 数据的时候,django 的 content_type 会拿到请求头中的 Content-Type 属性,然后根据值进行分析。
将 request.data 中的值放到 request.POST 中需要满足两个条件:
Content-Type:application/x-www-form-urlencoded
如果请求头中的 Content-Type:application/x-www-form-urlencoded,request.POST 中才有值(去 request.body 中解析数据)。
数据格式要求:
① 表单提交
form 表单提交时会自动的将请求头中的 Content-Type:application/x-www-form-urlencoded,数据也会自动转换为 ?parser=xxx&parser2=xxx 的格式。
<form action="/api/parser/" method="post"> <input type="text" name="parser"/> <input type="text" name="parser2"/> <input type="submit"/></form>
② ajax 提交
默认的请求头中 Content-Type:application/x-www-form-urlencoded
$.ajax({ url: ...,type: "POST",data: {name: yuntuan, age: 18 }})
情况一:
# body 有值,POST 无
$.ajax({
url: ...,
type: "POST",
headers: {"Content-Type": "application/json"},
data: {
name: yuntuan,
age: 18
}
})
情况二:
# body 有值,POST 无
# 这种情况下 request.body 有值,需要字节类型转换成字符串类型
# json.loads(request.body)
$.ajax({
url: ...,
type: "POST",
headers: {"Content-Type": "application/json"},
# 不在做内部转换,而是传递字符串
data: JSON.stringfy({
name: yuntuan,
age:18
})
})