json 从XMLHttpRequest函数写入HTML id

m3eecexj  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(78)

我现在正在努力使用JSON,我设法用这个JavaScript代码向php发送了一个请求,但我只能将结果写入一个警报事件。
我想将JSON写入一个HTML id,但是在哪里可以添加XXX.innerHTML =“MY OUTPUT”?
非常感谢各位这是我的代码。

type

<script>

window.addEventListener("load", () => {
  function sendData() {
    const XHR = new XMLHttpRequest();

    // Bind the FormData object and the form element
    const FD = new FormData(form);

    // Define what happens on successful data submission
    XHR.addEventListener("load", (event) => {
      alert(event.target.responseText);
    });

    // Define what happens in case of error
    XHR.addEventListener("error", (event) => {
      alert("Oops! Something went wrong.");
    });

    // Set up our request
    XHR.open("POST", "server.php");

    // The data sent is what the user provided in the form
    XHR.send(FD);
  }

  // Get the form element
  const form = document.getElementById("myForm");

  // Add 'submit' event handler
  form.addEventListener("submit", (event) => {
    event.preventDefault();

    sendData();
  });
});
</script>

 here

字符串
我对这部分有困难:

type// Define what happens on successful data submission
    XHR.addEventListener("load", (event) => {
      alert(event.target.responseText);
    }); here

nnvyjq4y

nnvyjq4y1#

如果你有一个 id=“container” 的元素,请尝试以下操作:

XHR.addEventListener("load", (event) => {
  const response = JSON.parse(event.target.responseText);
  const container = document.getElementById("container");

  //display the JSON response in the container
  container.innerHTML = JSON.stringify(response, null, 2);
});

字符串

相关问题