«

jQuery $.post()和fetch发送POST请求时PHP接收数据差异何在?

时间:2024-12-24 07:32     作者:emer     分类:


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中文网其它相关文章!