You need to enable JavaScript to run this app. 异步XMLHttpRequest GET回调内更新HTML 外部无法获取更新值问题
优惠活动
大模型
产品
解决方案
定价
更多

异步XMLHttpRequest GET回调内更新HTML 外部无法获取更新值问题

问题核心原因

  • XMLHttpRequest设置为异步模式(request.open的第三个参数为true),request.send()执行后不会等待请求返回结果,会直接执行后续代码,此时onload回调尚未触发,页面元素还未更新,所以读取到的是旧值。
  • window.onload仅在页面原生DOM、静态资源(图片、样式等)全部加载完成时触发,不会等待AJAX请求执行结束,因此写在window.onload中的逻辑也无法拿到请求更新后的内容。

解决方案

方案1:回调函数

将需要读取更新后内容的逻辑封装为回调函数,在onload回调、页面内容更新完成后执行:

function locationData(zip_code, afterUpdateCallback) {
  var request = new XMLHttpRequest(); 
  request.open("GET", url, true);
  request.send();
  request.onload = () => {
    if (request.status == 200) {
      const data = JSON.parse(request.response);
      document.getElementById("forecast").innerHTML = "Updated content";
      // 内容更新完成后执行传入的回调
      if (typeof afterUpdateCallback === 'function') {
        afterUpdateCallback();
      }
    } else {
      console.log("error");
    }
  }
}

// 调用时传入需要执行的后续逻辑
locationData('目标邮编', function() {
  console.log(document.getElementById("forecast").innerText); // 可正常获取更新后的内容
})

方案2:Promise + async/await

将请求逻辑封装为Promise,使用await等待请求完成、内容更新后再执行后续逻辑,代码可读性更高:

function locationData(zip_code) {
  return new Promise((resolve, reject) => {
    var request = new XMLHttpRequest(); 
    request.open("GET", url, true);
    request.send();
    request.onload = () => {
      if (request.status == 200) {
        const data = JSON.parse(request.response);
        document.getElementById("forecast").innerHTML = "Updated content";
        resolve();
      } else {
        reject('请求失败,状态码:' + request.status);
      }
    }
    request.onerror = () => reject('网络连接错误');
  })
}

// 调用时用async/await等待执行完成
async function execAfterUpdate() {
  try {
    await locationData('目标邮编');
    console.log(document.getElementById("forecast").innerText); // 可正常获取更新后的内容
  } catch (err) {
    console.log(err);
  }
}

execAfterUpdate();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:21:01