简体   繁体   English

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

[英]Sending data form from JavaScript to PHP, manipulate it, and sending it back to JavaScript with Fetch

This is my JS code:这是我的 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));
});
});

and test.php:和测试.php:

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

But as response I am getting an empty array.但作为回应,我得到一个空数组。

What's wrong with my code?我的代码有什么问题?

Try it:尝试一下:

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

If you just want the reponse data from the post, then you don't need the nested fetch with the GET.如果您只想要来自帖子的响应数据,那么您不需要使用 GET 进行嵌套提取。 Instead just read the post response:相反,只需阅读帖子回复:

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));
    });

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

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