javascript - 带有 HTTP PUT 的 JavaScript Fetch() 未将 FormData 发送到 PHP 服务器
问题描述
我正在使用 PHP REST API 将数据从 JS 客户端发布到 PHP 8 服务器。我正在使用JSfetch()
方法。当使用POST
formdata 被发送到 PHP 的全局 $_POST,但由于我需要更新数据我必须使用PUT
. 不知何故,谷歌浏览器没有将表单数据发送到服务器,我不知道为什么。有人知道原因吗?
JS: 常量 formData = new FormData(); formData.append('title', 'Hello world'); 常量选项 = { 方法:'PUT', 正文:JSON.stringify(formData); 缓存:'无缓存', 模式:'cors', 凭据:'同源', 重定向:'关注', 推荐人:'无推荐人', // 也不工作 // 标题:{ // '内容类型': 'application/json; 字符集=UTF-8;' // }, }; fetch('/some/api/v1', 选项);
PHP 8 服务器: var_dump($_REQUEST); // 无效的
解决方案
问题不在客户端,而在服务器。Firefox 和 Chrome 都将数据序列化并使用以下代码发送:
document.getElementById('myForm').addEventListener('submit', function(e){
e.preventDefault();
let fd = new FormData(this);
fetch('test.php', {method:'PUT', body:fd})
.then(function(response){
response.text().then(function(txt){console.log("Response:"+txt);});
});
});
问题在于 PHP 对 的支持PUT
,它不会自动为您解包数据。您可以从stdin
流中获取它。
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
while ($data = fread($putdata, 1024)) {
echo $data;
}
回复:
-----------------------------256278305409917102757952731
Content-Disposition: form-data;
name="myText" ffsssssdd
-----------------------------256278305409917102757952731--
如果要将表单数据作为 JSON 对象发送,可以使用:
const serialize_form = form => JSON.stringify(
Array.from(new FormData(form).entries())
.reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
);
const json = serialize_form(this);
fetch('test.php', {method:'PUT', body:json, headers:{'content-type':'application/json'}})
.then(function(response){
response.text().then(function(txt){console.log("Response:"+txt);});
});
回复:
{"myText":"ghfghfghfg"}
serialize_form
从这个答案中获取的功能
请参阅PHP 参考
推荐阅读
- database - 哪个千分尺度量更适合计算找到的数据库值?
- ubuntu - XRDP 未使用我的 .xinitrc 文件中指定的 DWM
- python-3.x - 如何在运行 apache2 的 mac 上将 python3 设置为 cgi
- algorithm - 如何解决矩阵的最小成本加权遍历
- ios - UITableView 没有从 Segue 加载数据
- android - 如何使用带有图标的手势检测器:[]
- python - 在 Python 的另一个页面中使用“类中的变量”
- ssis - 应该在错误处理或错误输出中添加通知错误的电子邮件任务?
- r - 查询 R 中的循环
- reactjs - 用样式组件编写反应组件哪个更好?