Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将数据表单从JavaScript发送到PHP,对其进行操作,并使用Fetch将其发送回JavaScript_Javascript_Php_Ajax_Http_Fetch - Fatal编程技术网

将数据表单从JavaScript发送到PHP,对其进行操作,并使用Fetch将其发送回JavaScript

将数据表单从JavaScript发送到PHP,对其进行操作,并使用Fetch将其发送回JavaScript,javascript,php,ajax,http,fetch,Javascript,Php,Ajax,Http,Fetch,这是我的JS代码: let report_button = document.getElementById("report_button"); report_button.addEventListener("click", e => { e.preventDefault(); let form = new FormData(document.getElementById("form")); fetch("test.php", { method: "POST", body

这是我的JS代码:

 let report_button = document.getElementById("report_button");

 report_button.addEventListener("click", e => {
 e.preventDefault();

let form = new FormData(document.getElementById("form"));

fetch("test.php", {
  method: "POST",
  body: form
}).then(res => {
  fetch("test.php", { method: "GET" })
    .then(response => response.text())
    .then(data => console.log(data));
});
});
和test.php:

<?php echo json_encode($_POST); ?>

但作为回应,我得到了一个空数组

我的代码怎么了?

试试看:

fetch("test.php", {
  method: "POST",
  body: form
}).then(res => {
  return res.json();
}).then(data => {
  console.log(data);
});

试试看:

fetch("test.php", {
  method: "POST",
  body: form
}).then(res => {
  return res.json();
}).then(data => {
  console.log(data);
});


如果您只需要post中的响应数据,那么不需要GET中的嵌套fetch。相反,只需阅读帖子回复:

fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      body: JSON.stringify({
        title: 'test 1',
        body: 'test 1',
        userId: 999
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    })
    .then(response => response.json())
    .then(json => {
      console.log('response: ' + JSON.stringify(json));
    });

如果您只需要post中的响应数据,那么不需要GET中的嵌套fetch。相反,只需阅读帖子回复:

fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      body: JSON.stringify({
        title: 'test 1',
        body: 'test 1',
        userId: 999
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    })
    .then(response => response.json())
    .then(json => {
      console.log('response: ' + JSON.stringify(json));
    });

在第二个请求中,您没有传递任何数据,因此没有任何数据可供输出。每个ajax请求都是一个全新的请求。也没有理由提出第二个请求。只需使用第一个请求的结果。将包含您发布到其中的数据。
echo file\u get\u contents('php://input');在第二个请求中,您没有传递任何数据,因此它没有任何输出。每个ajax请求都是一个全新的请求。也没有理由提出第二个请求。只需使用第一个请求的结果。将包含您发布到其中的数据。
echo file\u get\u contents('php://input');