[英]Sending data to PHP server with Fetch API (POST method and JSON preferred)
我第一次尝试获取 API,但将POST
数据发送到 PHP 服务器时遇到问题。
我正在远离$.ajax
并尝试纯 javascript 解决方案与不同的服务器进行通信(有时是本地的,有时不是)。 现在我试图理解 Fetch API ,即使它简单直观,我也偶然发现了一个奇怪而意想不到的问题:
我无法将 JSON 帖子发送到 PHP 服务器
我可以将表单数据发布到本地 PHP
我无法将表单数据发送到 WEB URL PHP
我可以(显然)从上述所有内容中检索数据,但奇怪的是什么都没有到达。 通过$_SERVER['REQUEST_METHOD']
我可以看到,当使用本地路径时,我得到了“POST”,但当使用 WEB URL 时,由于某种我不明白的原因,它在GET
中发生了变化。
url="/";
url="www.something.com";
fetch(url, {
method: 'POST',
body: JSON.stringify({
test: "toast",
})
})
.then(function(response) {
return response.text();
})
.then(function(data) {
console.log(data);
});
我希望只是以可靠和清晰的方式发送和接收数据。 没有 jquery,没有库等。我只想发送一个JSON {"test":"toast"}
并在检查$_POST
文件时在 PHP 文件中找到它
似乎本地和 web 网址的问题在于这种差异:www.something.com/test => www.something.com/test/index.php。 没有 index.php 出于某种原因它拒绝了 POST 数据(但无论如何都要读取回显信息)。 但是关于 JSON 的问题仍然存在。
我无法将 JSON 帖子发送到 PHP
我可以将表单数据发送到 PHP
我发现 $_POST 和 $_GET 不适用于 Fetch API。 您必须使用php://input来获取发送到服务器的所有数据。
不知道为什么。 有更好的解决方案吗? 为什么ajax和XMLHttpRequest没有这种问题?
注意:如果您希望数据被识别为 json,您必须使用 header 指定它,即使这从未被请求过,为什么现在? Fetch API 是否缺少某些内容?
header('Content-Type: application/json');
$test=json_decode(file_get_contents("php://input"));
//some code
echo json_encode($test);
Fetch API有两种使用方式:一>
let response = await fetch(url,[Options]);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);
}
第二种方法是使用纯 promise 语法:
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
.then(response => response.json())
.then(commits => alert(commits[0].author.login));
现在让我们谈谈选项和数据:您的数据必须是 JavaScript object ,如下所示:
let data = {
test: "toast",
};
然后你可以像这样配置你的标题:
let headers: {
"Content-Type": "application/json"
}
};
最后像这样使用 fetch :
let response = await fetch(url, {
method: "POST",
headers:headers,
body: JSON.stringify(data)
});
我认为您的问题是使用 FormData 而不是字符串化 JavaScript object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.