若是要在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