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);
相关文章
相关标签/搜索