登录
首页 >  文章 >  php教程

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

时间:2024-12-10 10:51:51 181浏览 收藏

文章不知道大家是否熟悉?今天我将给大家介绍《$.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 却失败?原因及解决方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>