PHP content-type為"application/json"的post過來的資料$_POST接受不到的問題

來源:互聯網
上載者:User

標籤: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接受不到的問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.