我第一次尝试使用Fetch API,但在将POST
数据发送到PHP服务器时遇到问题。
我正在离开$.ajax
,并尝试使用纯JavaScript解决方案与其他服务器(有时是本地,有时不是)进行通信。现在,我试图理解Fetch API,即使它简单直观,我还是偶然发现了一个奇怪而出乎意料的问题:
我无法将JSON帖子发送到PHP服务器
我可以将表单数据发布到本地PHP
我无法将表单数据发布到WEB URL PHP
我可以(显然)从以上所有内容中检索数据,但是很奇怪,什么也没有。通过$_SERVER['REQUEST_METHOD']
,我可以看到,当使用LOCAL路径时,按照我的要求得到“ POST”,但是由于某些我不理解的原因,当使用WEB URL时,它在GET
中发生了变化。
url="/";
url="www.something.com";
var formData = new FormData();
formData.append('test', 'toast');
fetch(url, {
method: 'POST',
body: formData
})
.then(function(response) {
return response.text();
})
.then(function(data) {
console.log(data);
}.bind(this));
我希望仅以可靠清晰的方式发送和接收数据。没有jquery,没有库等。我只想发送JSON {"test":"toast"}
并在检查$_POST
变量时在PHP文件上找到它。
有两种使用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对象:
let data = {
test: "toast",
};
然后您可以像这样配置标题:
let headers: {
"Content-Type": "application/json"
}
};
最终使用这样的访存:
let response = await fetch(url, {
method: "POST",
headers:headers,
body: JSON.stringify(data)
});
我认为您的问题是使用FormData而不是字符串化的JavaScript对象