
jquery $.post() 和 fetch 发送 post 请求的差异
在 php 中,判断是否为 post 请求的方法是检查 $_server[‘request_method’]。然而,前端代码中,jquery 的 $.post() 和 fetch 发送 post 请求时却出现了不同的情况。
问题原因
$_post 超全局变量只能获取 application/x-www-form-urlencoded 和 multipart/form-data 类型的表单数据。而 fetch 发送的 json 数据需要通过 php://input 获取并解析。
立即学习“PHP免费学习笔记(深入)”;
解决方案
有多种方法解决这个问题:
1. 修改前端代码
将 application/json 修改为 application/x-www-form-urlencoded;charset=utf-8 并使用 qs 包对数据进行序列化:
fetch('http://localhost/', { method: 'post', headers: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' }, body: qs.stringify({ action: 'send_data', ... })}).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') {}}
以上就是jQuery $.post()与Fetch发送POST请求:PHP后端如何正确接收数据?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1251221.html
微信扫一扫
支付宝扫一扫