在沒有特別修改程式的情況下,php 會拿不到 angularjs post 的資料,主要是因為在 post 傳送時,二者定義用的 content-type 不同,所以就發生拿不到資料的問題。
那不同的地方在哪裡呢?
首先來看AngularJS,
AngularJS 預設是用 content-type = application/json 來傳送資料,傳送的格式會變成:
POST / HTTP/1.1
Content-Type: application/json
{'id':'12341234'}
再來是PHP,
PHP 的 $_POST 是用 content-type = application/x-www-form-urlencoded 來接收資料,接收的格式會變成:
POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
id=12341234
不同的content-type,就有不同的request message body。
可以參考前輩的說明:
What's the difference between “Request Payload” vs “Form Data” as seen in Chrome dev tools Network tab
所以解決方式有二:
- AngularJS改用application/x-www-form-urlencoded來傳送資料。
- PHP改用application/json來接收資料。
0 意見:
張貼留言