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

为何无法立即将responseText存入变量?如何获取目标响应值?

问题原因与解决方案

原因

XMLHttpRequest是异步操作:调用xhr.send()后,浏览器会在后台处理请求,主线程不会等待响应返回,会直接执行后续的let a = xhr.responseText。此时请求还未完成,responseText是空字符串,自然获取不到目标响应值{"success":"true"}。

解决方法

方法1:将赋值逻辑放入回调函数内

直接把变量赋值操作移到onreadystatechange的回调里,确保只有当响应完全返回后才执行赋值:

let xhr = new XMLHttpRequest();
let a; // 提前声明变量

xhr.open("GET", "https://reqbin.com/echo/get/json");

xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    console.log(xhr.responseText);
    a = xhr.responseText; // 响应返回后再赋值
    // 所有需要使用a的逻辑都要放在这里或者之后
    console.log(a); // 此时能正常获取到{"success":"true"}
  }
};

xhr.send();

方法2:用Promise封装(更易维护)

把XHR逻辑封装成Promise,结合async/await让异步代码看起来更像同步写法:

function fetchData(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        // 同时判断状态码确保请求成功
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(xhr.responseText);
        } else {
          reject(new Error(`请求失败,状态码:${xhr.status}`));
        }
      }
    };
    xhr.send();
  });
}

// 使用async/await调用
async function getData() {
  try {
    const a = await fetchData("https://reqbin.com/echo/get/json");
    console.log(a); // 成功获取响应值
  } catch (err) {
    console.error(err); // 处理请求失败的情况
  }
}

getData();

方法3:使用Fetch API(现代替代方案)

Fetch是浏览器原生的异步请求API,语法更简洁,推荐优先使用:

async function getData() {
  try {
    const response = await fetch("https://reqbin.com/echo/get/json");
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    const a = await response.text(); // 如果需要JSON对象,改用await response.json()
    console.log(a);
  } catch (err) {
    console.error(err);
  }
}

getData();

内容的提问来源于stack exchange,提问作者아잉쿠

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:55:25