標籤:header title ica style 前端 origin har sid axios
ajax預設是以application/x-www-form-urlencoded方式提交。也就是常見的表單提交方式。在PHP中使用$_POST方式可以輕鬆擷取。
但如果將ajax的要求標頭強制指定為application/json,那麼你的$_POST就接受不到了。必須使用$GLOBALS[‘HTTP_RAW_POST_DATA‘]取出來,然後再json_decode就行了。
如fetch、axios預設的要求標頭就是application/json,所以要注意一下。
還有一些的細節需要瞭解一下
1、後端必須允許前端定義Content-Type之類的頭請求。
header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘);
2、php中exit的輸出只允許字串。所以要輸出什麼之前最好使用(string)轉義一下。
3、如果使用ajax的application/json方式,記得data參數是字串類型的。使用JSON.stringify()轉換一下。
jquery ajax的代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script></head><body> <script> $(function () { $.ajax({ type:"post", url:"http://localhost:8080/news.php", data: JSON.stringify({ newsid: 101 }), headers: { "Content-type": "application/json; charset=utf-8" }, success: function (data) { console.log(data) } }) }) </script></body></html>
php代碼:
<?phpheader("Access-Control-Allow-Origin:*"); header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘); $rws_post = $GLOBALS[‘HTTP_RAW_POST_DATA‘];$mypost = json_decode($rws_post);$newsid = (string)$mypost->newsid;exit($newsid);
PHP content-type為"application/json"的post過來的資料$_POST接受不到的問題