PHP content-type爲"application/json"的post過來的數據$_POST接受不到的問題

ajax默認是以application/x-www-form-urlencoded方式提交。也就是常見的表單提交方式。在PHP中使用$_POST方式能夠輕鬆獲取。php

但若是將ajax的請求頭強制指定爲application/json,那麼你的$_POST就接受不到了。必須使用$GLOBALS['HTTP_RAW_POST_DATA']取出來,而後再json_decode就好了。css

如fetch、axios默認的請求頭就是application/json,因此要注意一下。html


 

還有一些的細節須要瞭解一下前端

一、後端必須容許前端定義Content-Type之類的頭請求。jquery

header('Access-Control-Allow-Headers:x-requested-with,content-type'); 

二、php中exit的輸出只容許字符串。因此要輸出什麼以前最好使用(string)轉義一下。ios

三、若是使用ajax的application/json方式,記得data參數是字符串類型的。使用JSON.stringify()轉換一下。ajax

 


 

jquery ajax的代碼:json

複製代碼
<!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代碼:axios

複製代碼
<?php
header("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);
相關文章
相關標籤/搜索