You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将XMLHttpRequest返回的JSON结果写入指定HTML元素?

解决方法

你需要在XHR的load事件回调函数里替换原有的alert代码,添加写入HTML元素的逻辑,具体修改如下:

修改后的核心代码片段

// Define what happens on successful data submission
XHR.addEventListener("load", (event) => {
  // 1. 获取PHP返回的响应内容
  const responseData = event.target.responseText;
  // 2. 找到你要写入内容的HTML元素(替换成你的目标元素ID)
  const targetElement = document.getElementById("resultContainer");
  // 3. 将内容写入元素:如果是JSON,格式化后展示更清晰
  targetElement.innerHTML = `<pre>${JSON.stringify(JSON.parse(responseData), null, 2)}</pre>`;
});

细节说明

  • 把resultContainer替换成你实际要使用的HTML元素ID,比如你页面里的<div id="jsonOutput"></div>就写document.getElementById("jsonOutput")
  • 如果不需要格式化JSON,直接用targetElement.innerHTML = responseData;即可
  • 确保PHP返回的是标准JSON格式,否则JSON.parse会报错;若返回的是普通文本,去掉JSON.parse和JSON.stringify部分

完整修改后的JS代码

<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) => {
      const responseData = event.target.responseText;
      const targetElement = document.getElementById("resultContainer");
      targetElement.innerHTML = `<pre>${JSON.stringify(JSON.parse(responseData), null, 2)}</pre>`;
    });

    // 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>

内容的提问来源于stack exchange,提问作者Monkeybus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 10:02:48