原链接 https://www.cnblogs.com/CyLee/p/7644380.html
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 代码:
<?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);
正文完
有偿技术支持加微信

发表至: PHP编码
2023-08-30