$.post() 发送成功,fetch 却失败?原因及解决方法

$.post() 发送成功,fetch 却失败?原因及解决方法

$.post() 成功发送数据,fetch 却失败的原因

使用 jquery $.post() 发送数据成功,而使用 fetch 失败,原因在于:

php 的 $_post 超全局变量只能获取 application/x-www-form-urlencoded 和 multipart/form-data 类型的表单数据。对于 json 及其他类型的数据,需要从 php://input 获取并进行解析。

要解决这个问题,你可以选择以下方法之一:

1. 修改前端代码

将 fetch 请求的 content-type 修改为 application/x-www-form-urlencoded 并使用 qs 包对数据进行转换,如下:

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))

2. 修改后端代码

在后端代码中,添加从 php://input 获取并解析 json 数据的代码:

$input = json_decode(file_get_contents('php://input'), true) ?: [];if ($_SERVER['REQUEST_METHOD'] == 'POST') {    if (@$input['action'] == 'send_data') {}}

以上就是$.post() 发送成功,fetch 却失败?原因及解决方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1283475.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月10日 23:53:52
下一篇 2025年12月10日 23:54:15

相关推荐

发表回复

登录后才能评论
关注微信