在django中獲取post數據,首先要規定post發送的數據類型是什么。
1.獲取POST中表單鍵值數據
如果要在django的POST方法中獲取表單數據,則在客戶端使用JavaScript發送POST數據前,定義post請求頭中的請求數據類型:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
在django的views.py相關方法中,需要通過request.POST獲取表單的鍵值數據,並且可以通過reques.body獲取整個表單數據的字符串內容
if(request.method == 'POST'): print("the POST method") concat = request.POST postBody = request.body print(concat) print(type(postBody)) print(postBody)
相關日志:
the POST method <QueryDict: {u'username': [u'abc'], u'password': [u'123']}> <type 'str'> username=abc&password=123
2.獲取POST中json格式的數據
如果要在django的POST方法中獲取json格式的數據,則需要在post請求頭中設置請求數據類型:
xmlhttp.setRequestHeader("Content-type","application/json");
在django的views.py中導入python的json模塊(import json),然后在方法中使用request.body獲取json字符串形式的內容,使用json.loads()加載數據。
if(request.method == 'POST'): print("the POST method") concat = request.POST postBody = request.body print(concat) print(type(postBody)) print(postBody) json_result = json.loads(postBody) print(json_result)
相關日志:
the POST method <QueryDict: {}> <type 'str'> {"sdf":23} {u'sdf': 23}