1. 程式人生 > >【轉】Django中使用POST方法獲取POST數據

【轉】Django中使用POST方法獲取POST數據

class 需要 request www ict .html bsp 請求 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 requests.method == ‘POST‘:
        print("the POST method")
        postAll = requests.POST
        postBody = requests.body
        print(postAll)
        postBodyStr = postBody.decode(‘utf-8‘)
        print(postBodyStr)

相關結果

the POST method
<QueryDict: {b: [2], a: [1]}>
a=1&b=2

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 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"))

相關結果:

the POST method
<QueryDict: {}>
{‘name‘: ‘baoshan‘}
----------------------------------------------------------------------------------------------------
baoshan

【參考】:http://www.cnblogs.com/zhangdewang/p/9222952.html

【轉】Django中使用POST方法獲取POST數據