Fetch - sending POST data

时间:2017-04-13 14:55:55

标签: fetch fetch-api

My PHP script isn't receiving anything via POST from fetch. What am I doing wrong?

Javascript:

fetch("http://127.0.0.1/script.php", {
    method: "post",
    body: "inputs=" + JSON.stringify({param: 7})
  }).then(response => response.json()).then(response => {
    console.log(response);
});

script.php:

  echo "\nprinting POST:\n";
  print_r($_POST);

  echo "\nprinting GET:\n";
  print_r($_GET);
  die();

Console:

printing POST: Array ( )

printing GET: Array ( )

2 个答案:

答案 0 :(得分:0)

您没有添加任何url参数(因此$_GET为空)并且您没有设置Content-Type标头,这将使PHP自动解析请求正文。 (因此$_POST为空)。

答案 1 :(得分:0)

该特定测试PHP文件的htaccess文件有问题。我用它来发布主项目文件夹/ PHP文件的东西,它就没问题了。