简体   繁体   English

使用 Fetch API 将数据发送到 PHP 服务器(首选 POST 方法和 JSON)

[英]Sending data to PHP server with Fetch API (POST method and JSON preferred)

I'm trying Fetch API for the first time and I have problems sending POST data to a PHP server.我第一次尝试获取 API,但将POST数据发送到 PHP 服务器时遇到问题。

I'm moving away from $.ajax and trying pure javascript solutions to communicate with different servers (sometimes local, sometimes not).我正在远离$.ajax并尝试纯 javascript 解决方案与不同的服务器进行通信(有时是本地的,有时不是)。 Now I'm trying to understand Fetch API and, even if it's simple and intuitive, I've stumbled on a weird and unexpected problem:现在我试图理解 Fetch API ,即使它简单直观,我也偶然发现了一个奇怪而意想不到的问题:

  • I CAN'T send JSON post to PHP server我无法将 JSON 帖子发送到 PHP 服务器

  • I CAN send form-data post to LOCAL PHP我可以将表单数据发布到本地 PHP

  • I CAN'T send form-data post to WEB URL PHP我无法将表单数据发送到 WEB URL PHP

I can (obviously) retrieve data from all the above, but strangely nothing arrives.我可以(显然)从上述所有内容中检索数据,但奇怪的是什么都没有到达。 Through $_SERVER['REQUEST_METHOD'] I can see that when using the LOCAL path I get "POST" as I asked, but when using the WEB URL it changes in GET for some reason I don't understand.通过$_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);
});

I expect just to send and receive data in a solid and clear way.我希望只是以可靠和清晰的方式发送和接收数据。 No jquery, no libraries, etc. I just want to send a JSON {"test":"toast"} and find it on the PHP file when checking the $_POST var.没有 jquery,没有库等。我只想发送一个JSON {"test":"toast"}并在检查$_POST文件时在 PHP 文件中找到它

UPDATE更新

It seems that the problem with local and web urls were on this difference: www.something.com/test => www.something.com/test/index.php.似乎本地和 web 网址的问题在于这种差异:www.something.com/test => www.something.com/test/index.php。 Without index.php for some reason it refused the POST data (but read the echoed info anyway).没有 index.php 出于某种原因它拒绝了 POST 数据(但无论如何都要读取回显信息)。 But the problem about JSON remain.但是关于 JSON 的问题仍然存在。

  • I CAN'T send JSON post to PHP我无法将 JSON 帖子发送到 PHP

  • I CAN send form-data post to PHP我可以将表单数据发送到 PHP

UPDATE更新

I found that $_POST and $_GET don't work well with Fetch API.我发现 $_POST 和 $_GET 不适用于 Fetch API。 You have to use php://input to get all the data sent to the server.您必须使用php://input来获取发送到服务器的所有数据。

Don't know why.不知道为什么。 There's a better solution?有更好的解决方案吗? Why ajax and XMLHttpRequest don't have this kind of problems?为什么ajax和XMLHttpRequest没有这种问题?

Note: If you want the data to be recognized as json, you have to specify it with a header, even this was never requested so why now?注意:如果您希望数据被识别为 json,您必须使用 header 指定它,即使这从未被请求过,为什么现在? Is Fetch API missing something? Fetch API 是否缺少某些内容?

header('Content-Type: application/json');

$test=json_decode(file_get_contents("php://input"));
//some code
echo json_encode($test);

There is two ways to use Fetch API: one> 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);
}

and the second way is to use pure promise syntax:第二种方法是使用纯 promise 语法:

fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));

now lets talk about options and data: your data must be a JavaScript object like this:现在让我们谈谈选项和数据:您的数据必须是 JavaScript object ,如下所示:

      let data = {
        test: "toast",
      };

then you can config your headers like this:然后你可以像这样配置你的标题:

let headers: {
       "Content-Type": "application/json"
      }
  };

finally use fetch like this:最后像这样使用 fetch :

let response = await fetch(url, {
        method: "POST",
        headers:headers,
        body: JSON.stringify(data)
      });

I think your problem is using FormData instead of stringified JavaScript object我认为您的问题是使用 FormData 而不是字符串化 JavaScript object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM