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

同域环境下XMLHttpRequest响应body为空问题求助

解决XMLHttpRequest responseText为空的问题

问题核心在于你使用的是异步XMLHttpRequest(open方法第三个参数为true),调用send()后请求会在后台异步执行,此时立即打印xhr.responseText,请求还未完成,自然拿到空字符串。虽然浏览器网络面板能看到最终的响应内容,但那是请求结束后的结果,和你代码执行的时机不匹配。

修复方案:

  • 监听load事件(推荐):在请求完成后再读取响应
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/api/"+id, true);
// 请求完成后触发load事件
xhr.onload = function() {
  // 先判断请求是否成功
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(xhr.responseText); // 此处可获取完整响应
  } else {
    console.error('请求失败,状态码:', xhr.status);
  }
};
xhr.send(null);
  • 监听readystatechange事件:通过readyState判断请求阶段
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/api/"+id, true);
xhr.onreadystatechange = function() {
  // readyState为4表示请求已完成,同时判断状态码正常
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send(null);
  • 使用现代的fetch API:代码更简洁,支持Promise和async/await
async function fetchTargetData() {
  try {
    const response = await fetch(`https://example.com/api/${id}`);
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    const responseText = await response.text();
    console.log(responseText);
  } catch (err) {
    console.error('请求出错:', err);
  }
}
fetchTargetData();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:54:25