最近在使用 thinkphp 開發(fā)項(xiàng)目的時(shí)候,遇到了一個(gè)問(wèn)題:提交表單后,無(wú)法獲取到 post 數(shù)據(jù)。這在開發(fā)過(guò)程中是比較常見的問(wèn)題,有些時(shí)候我們會(huì)感到十分困惑,尤其是在網(wǎng)上找了許多方法仍然沒能解決問(wèn)題的時(shí)候。本文將簡(jiǎn)單介紹如何解決這個(gè)問(wèn)題。
一、問(wèn)題現(xiàn)象
提交表單后,通過(guò) request->param() 或 $this->request->param() 獲取不到 post 數(shù)據(jù),得到的是空數(shù)組。
二、問(wèn)題原因
- 表單中沒有設(shè)置 enctype 屬性
在表單提交時(shí),如果 enctype 屬性沒有設(shè)置,那么默認(rèn)的數(shù)據(jù)傳輸方式是 application/x-www-form-urlencoded。此時(shí),post 的數(shù)據(jù)會(huì)放在 http 請(qǐng)求頭中,而不是請(qǐng)求體中。所以,在獲取 post 數(shù)據(jù)時(shí),我們需要使用 $this->request->post() 或者 request()->post()。
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
- 接口調(diào)用時(shí)沒有設(shè)置請(qǐng)求頭
在接口調(diào)用時(shí),我們需要設(shè)置相應(yīng)的請(qǐng)求頭,比如 Content-Type:application/json,否則服務(wù)器無(wú)法解析數(shù)據(jù)。如果沒有設(shè)置 Content-Type,則服務(wù)器默認(rèn)為 application/x-www-form-urlencoded,而此時(shí) post 的數(shù)據(jù)會(huì)放在 http 請(qǐng)求頭中,而不是請(qǐng)求體中,導(dǎo)致無(wú)法正確獲取 post 數(shù)據(jù)。
三、解決方法
- 設(shè)置 enctype 屬性
在表單中添加 enctype=”multipart/form-data”,這樣就能夠正確獲取 post 數(shù)據(jù)了。
- 設(shè)置請(qǐng)求頭
在接口調(diào)用時(shí),可以使用 cURL 設(shè)置請(qǐng)求頭。示例代碼如下:
$data = array( 'username' => 'admin', 'password' => '123456' ); $url = 'http://www.example.com/login'; $ch = curl_init(); $header = array( 'Content-Type: application/json', 'Content-Length: '.strlen(json_encode($data)) ); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($ch); curl_close($ch);
四、總結(jié)
無(wú)法獲取 post 數(shù)據(jù)是一個(gè)常見的問(wèn)題,出現(xiàn)這種情況一般都是由于數(shù)據(jù)傳輸方式或請(qǐng)求頭設(shè)置不正確導(dǎo)致的。如果遇到這個(gè)問(wèn)題,可以根據(jù)上述方法逐一解決,當(dāng)然也可以使用其他方法,如:使用 php://input 或者 $_POST 等獲取 post 數(shù)據(jù)的方式。最后,希望本文能夠解決讀者們?cè)陂_發(fā)過(guò)程中遇到的類似問(wèn)題。