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

JavaScript新手如何将XMLHttpRequest获取的innerHTML保存为可用字符串?

问题原因

XMLHttpRequest 是异步操作,你在回调函数内定义的code属于局部变量,且回调函数的执行时机晚于外层同步代码,因此无法直接在函数外部拿到该值使用。另外补充注意:如果你是在 Node.js 环境运行代码(用到了require("xmlhttprequest")),环境不存在浏览器的document对象,你注释掉的xhr.responseText才是请求返回的响应内容,document.getElementById写法仅在浏览器环境生效。


解决方案(推荐用 Promise + async/await 封装)

function getBasketCode() {
  return new Promise((resolve, reject) => {
    // 浏览器环境可删除下面这行require,原生自带XMLHttpRequest
    const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState === xhr.DONE) {
        if (xhr.status >= 200 && xhr.status < 300) {
          // Node.js环境用这行拿响应内容
          const code = xhr.responseText;
          // 浏览器环境如果要拿请求返回页面里的指定DOM,用下面这段替换
          // const parser = new DOMParser();
          // const doc = parser.parseFromString(xhr.responseText, 'text/html');
          // const code = doc.getElementById("shoppingcart_filled").innerHTML;
          resolve(code);
        } else {
          reject(new Error(`请求失败,状态码:${xhr.status}`));
        }
      }
    };
    xhr.open('GET', 'https://www.xxxxx.nl/xxxx', true);
    xhr.send();
  });
}

// 调用方式
async function handleCode() {
  try {
    const targetStr = await getBasketCode();
    // 所有需要用到该字符串的后续逻辑都写在这里
    console.log('获取到的字符串:', targetStr);
  } catch (err) {
    console.error('请求出错:', err);
  }
}
handleCode();

注意事项

  • 所有需要用到该返回字符串的逻辑,必须等异步请求完成后执行,不能在getBasketCode()调用后同步取值,此时请求还未返回,值为undefined
  • 如果是在浏览器端运行,不需要引入xmlhttprequest模块,删除对应require行即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:21:00