Отправка формы данных с JavaScript на PHP, манипулирование ею и отправка обратно на JavaScript с помощью Fetch - PullRequest
1 голос
/ 22 января 2020

Это мой 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));
});
});

и проверка. php:

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

Но в ответ я получаю пустой массив.

Что не так с моим кодом?

Ответы [ 2 ]

0 голосов
/ 22 января 2020

Если вы просто хотите получить данные об ответе из поста, то вам не нужна вложенная выборка с GET. Вместо этого просто прочитайте ответ:

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));
    });
0 голосов
/ 22 января 2020

Попробуйте:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...