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

如何在单个JS文件中正确发起多个XMLHttpRequest请求?

问题原因与解决方案

你的问题出在使用了同步XMLHttpRequest(open方法的第三个参数设为false)。同步请求会阻塞JavaScript主线程,直到第一个请求完全结束才会执行后续代码。如果第一个请求出现延迟或卡住,第二个请求根本无法启动,这就是第二个请求一直处于加载状态的核心原因。而且现在主流浏览器对同步XHR有诸多限制,不推荐在实际项目中使用。


正确的异步请求方式

1. 传统异步XMLHttpRequest写法

将请求设为异步(第三个参数改为true),通过onload事件处理响应,这样两个请求可以并行发起,不会阻塞线程:

function cacheobject(){
  let req = new XMLHttpRequest();
  req.open('get', 'http://localhost:3000/cache', true); // 开启异步模式
  req.onload = function() {
    // 检查请求是否成功
    if (req.status >= 200 && req.status < 300) {
      console.log(req.responseText);
    } else {
      console.error('cache请求失败,状态码:', req.status);
    }
  };
  // 处理网络错误
  req.onerror = function() {
    console.error('cache请求网络出错');
  };
  req.send(null);
};

function roomprcieCache(){
  let req = new XMLHttpRequest();
  req.open('get', 'http://localhost:3000/roomcache', true);
  req.onload = function() {
    if (req.status >= 200 && req.status < 300) {
      console.log('My mumu don finish');
      console.log(req.responseText);
    } else {
      console.error('roomcache请求失败,状态码:', req.status);
    }
  };
  req.onerror = function() {
    console.error('roomcache请求网络出错');
  };
  req.send(null);
};

// 并行发起两个请求
cacheobject();
roomprcieCache();

2. 现代fetch + async/await写法

fetch是浏览器原生的Promise-based API,结合async/await可以让异步代码看起来像同步代码,更简洁易读:

async function cacheobject() {
  try {
    const response = await fetch('http://localhost:3000/cache');
    // 检查响应状态是否正常
    if (!response.ok) {
      throw new Error(`cache请求失败:${response.status}`);
    }
    const data = await response.text();
    console.log(data);
    return data;
  } catch (error) {
    console.error(error.message);
  }
}

async function roomprcieCache() {
  try {
    const response = await fetch('http://localhost:3000/roomcache');
    if (!response.ok) {
      throw new Error(`roomcache请求失败:${response.status}`);
    }
    const data = await response.text();
    console.log('My mumu don finish');
    console.log(data);
    return data;
  } catch (error) {
    console.error(error.message);
  }
}

// 并行执行两个请求
cacheobject();
roomprcieCache();

// 如果需要按顺序执行(先完成第一个再执行第二个),可以用自执行异步函数:
// (async () => {
//   await cacheobject();
//   await roomprcieCache();
// })();

注意事项

  • 禁止使用同步XMLHttpRequest,它会导致页面卡顿,影响用户体验,且浏览器对其的支持正在逐步限制。
  • 实际项目中也可以使用成熟的HTTP库(如axios),进一步简化请求逻辑,处理拦截、错误统一处理等场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:55:31