且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-01 17:00:37

有两种使用Fetch API的方法:一个>

There is two ways to use Fetch API: one>

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语法:

and the second way is to use pure promise syntax:

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

现在让我们讨论一下选项和数据:您的数据必须是这样的JavaScript对象:

now lets talk about options and data: your data must be a JavaScript object like this:

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

然后您可以按以下方式配置标题:

then you can config your headers like this:

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

最终像这样使用获取:

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

我认为您的问题是使用FormData而不是字符串化的JavaScript对象

I think your problem is using FormData instead of stringified JavaScript object