香草 JavaScript 异步多个 xhr.open()

Vanilla JavaScript async multiple xhr.open()

我想知道如何使用 vanilla JS 处理多个 xhr 请求。我想打开多个 html 模板并在所有模板准备就绪后加载页面。当我使用很少的 xhr.open() 请求时,它只会 return 1 个模板:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
    if(xhr.status === 200){
        storage.append(xhr.responseText);
    }
}
function getAsync(url) {
    xhr.open('get', url);
    xhr.send();
}
getAsync('localhost:3000/template1.html');
getAsync('localhost:3000/template2.html');

我知道 .open() 只能在 time 上工作 1。 那么是否可以异步加载所有模板,或者我应该同步加载一个接一个?另外,我想知道我是否应该创建多个 xhr = new XMLHttpRequest() 对象以便我可以 运行 多个 .open()?

谢谢

您正在使用一个变量来定义 xhr 请求,并使用了该变量两次,因此第二次覆盖了该变量。您需要创建一个循环并使用 let xhr; 而不是 var xhr,因为 let 具有块作用域,因此循环中的每个实例都将被独立定义。

即像

// Create iterable list of URLS
let urls = ['localhost:3000/template1.html', 'localhost:3000/template2.html'];

// Loop through URLs and perform request
for(let i=0; i<urls.length; i++) {
    let xhr = new XMLHttpRequest();

    xhr.onload = function() {
        if(xhr.status === 200){
            storage.append(xhr.responseText);
        }
    }

    xhr.open('get', urls[i]);
    xhr.send();
}