django中使用POST方法 獲取POST數據


在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}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM