本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

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

网络教程 app 1℃

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

jquery $.post() 与 fetch 发送数据时为何表现不同?

在使用 $_post 超全局变量处理 post 数据时,php 只支持 application/x-www-form-urlencoded 和 multipart/form-data 类型的表单数据。

然而,fetch 默认发送的是 json 数据,其请求头为 application/json。因此,即使前端代码使用 fetch 发送数据,也无法通过 $_post 正常获取。

解决方法:

前端:

修改发送数据的请求头为 application/x-www-form-urlencoded,同时使用 qs 包将数据序列化。

fetch(‘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))

后端:

使用 php://input 获取 post 数据并解析为数组。

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

以上就是jQuery $.post()和fetch发送POST请求时PHP接收数据差异何在?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » jQuery$.post()和fetch发送POST请求时PHP接收数据差异何在?

喜欢 (0)