javascript - 另一个 $_POST 没有从 Javascript 的 Fetch() 中检索数据(但 ajax 确实...)(已解决)
问题描述
已解决:我忘记将数据添加到 fetch...
我终于迈出了 ajax & co 的一步...查找了这些东西,并想使用更新的 fetch 机制,但这没有用....服务器端的 $_POST 仍然令人沮丧地空着。 ...我切换到 ajax,使用相同的服务器,几乎相同的代码,它可以工作!
所以我有一个可行的解决方案,但是,知道应该起作用的东西却不令人满意,但……如果有人有解决方案?
让我们从 php 模型开始:
testsave.php:
<?php
print("POST = ".print_r($_POST,true));
print("inputstream :".file_get_contents('php://input')."\n");//maybe here??
?>
和test.php:
<html>
<header>
<link rel="icon" href="favicon.svg">
</header>
<body>
<form method="post" onsubmit="return withajax('testsave.php','testfield');">
<input type="text" id="testfield"/>
<input type="submit" value="ok"/>
</form>
<script>
function withajax(filename, fieldname)
{
let data = new FormData();
data.append(fieldname, document.getElementById(fieldname).value);
var xhr = new XMLHttpRequest();
xhr.open("POST", filename);
xhr.onload = function()
{
document.getElementById(fieldname).value = this.response;
console.log(this.response);
};
xhr.send(data);
return false;
}//function withajax(filename)
function withfetch(filename, fieldname)
{
let data = new FormData();
data.append(fieldname, document.getElementById(fieldname).value);
let configObj =
{
method: "POST",
//cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
//credentials: 'same-origin', // include, *same-origin, omit
body: data
};
fetch(filename,configObj) //<-- edit without adding the data, it won't work....
.then(function (response)
{
return response.text();
})
.then(function (text)
{
document.getElementById(fieldname).value = text;
console.log("response = "+text);
})
.catch(function (error)
{
console.log("Error : "+error);
});
return false;
}//function withfetch(filename)
</script>
</body>
</html>
如果在表单的onsubmit中我放了withajax,它就可以工作,如果我放withfetch,php脚本中的$_POST中什么都没有......
解决方案
推荐阅读
- python - 通过搜索用户名从文件中获取密码并将该密码存储在变量中
- javascript - 在选定下拉列表的两个值之间计算?
- javascript - 重新编译 build.py 文件时缺少 goog.date 提供程序 - google blockly
- sql - 更改参考数据库表的输入值
- angular - 为什么从父组件发出后子组件中的值没有改变?
- laravel - 在刀片(Laravel)中显示来自其他模型的属性
- google-apps-script - 通过 google sheet 脚本删除 ", + 和类似字符
- javascript - 在 Angular 组件中添加和删除聊天机器人脚本标签以仅显示在某些页面上
- date - 在 Delphi 中计算 24 小时或日期更改
- javascript - 在运行“npm run prod”时,在 Laravel reactjs 中得到这个“CssSyntaxError: /css/style.css:118:18: Missed semicolon”