Vanilla JavaScript async multiple xhr.open()

问题描述 投票:0回答:1

我想知道如何使用vanilla JS处理多个xhr请求。我想打开多个html模板并在所有这些模板都准备就绪时加载页面。当我使用几个xhr.open()请求时,它只会返回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。那么是否可以异步加载所有teamplate或者我是否应该在同步事件中一个接一个地加载?另外,我想知道,如果我应该创建多个xhr = new XMLHttpRequest()对象,以便我可以运行多个.open()

谢谢

javascript ajax asynchronous xmlhttprequest ecmascript-5
1个回答
1
投票

您正在使用一个变量来定义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();
}
© www.soinside.com 2019 - 2024. All rights reserved.