若是要在django的POST方法中获取表单数据,则在客户端使用JavaScript发送POST数据前,定义post请求头中的请求数据类型:html
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
在django的views.py相关方法中,须要经过request.POST获取表单的键值数据,而且能够经过reques.body获取整个表单数据的字符串内容python
if requests.method == 'POST': print("the POST method") postAll = requests.POST postBody = requests.body print(postAll) postBodyStr = postBody.decode('utf-8') print(postBodyStr)
相关结果django
the POST method <QueryDict: {'b': ['2'], 'a': ['1']}> a=1&b=2
若是要在django的POST方法中获取json格式的数据,则须要在post请求头中设置请求数据类型: json
xmlhttp.setRequestHeader("Content-type","application/json");
在django的views.py中导入python的json模块(import json),而后在方法中使用request.body获取json字符串形式的内容,使用json.loads()加载数据。app
if requests.method == 'POST': print("the POST method") postAll = requests.POST postBody = requests.body print(postAll) postBodyStr = postBody.decode('utf-8') json_result = json.loads(postBodyStr) print(json_result) print('-'*100) print(json_result.get("name"))
相关结果:post
the POST method <QueryDict: {}> {'name': 'baoshan'} ---------------------------------------------------------------------------------------------------- baoshan