
jquery $.post() 与 fetch 发送数据时为何表现不同?
在使用 $_post 超全局变量处理 post 数据时,php 只支持 application/x-www-form-urlencoded 和 multipart/form-data 类型的表单数据。
然而,fetch 默认发送的是 json 数据,其请求头为 application/json。因此,即使前端代码使用 fetch 发送数据,也无法通过 $_post 正常获取。
解决方法:
立即学习“PHP免费学习笔记(深入)”;
前端:
fetch('http://localhost/', {
method: 'post',
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
},
body: qs.stringify({
action: 'send_data',
talk_code: '11223344',
cid: '27',
token: 'crx',
content: '这是一条测试内容~~',
})
}).then(res => res.text()).then(json => console.log(json))后端:
$input = json_decode(file_get_contents('php://input'), true) ?: [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (@$input['action'] == 'send_data') {}
}以上就是jQuery $.post()和fetch发送POST请求时PHP接收数据差异何在?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号