FSS FSS - 3 months ago 15
Javascript Question

(beginner javascript) get multiple text files xml request

Very grateful if someone can help me out with the syntax here- I am hoping to make several XML requests, each time getting a different text file. Here is the general structure of my code. How can I get each file in turn (f0, f1 and f2)?

window.onload = function(){

var f = (function(){
var xhr = [];
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
f0 = "0.txt"
f1 = "1.txt"
f2 = "2.txt"
//??? xhr[i].open("GET", file i, true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
//do stuff
}
};
xhr[i].send();
})(i);
}
})();

};

Answer

Simply put your filenames in an array.

window.onload = function(){

var f = (function(){
    var xhr = [];
    var files = ["f0.txt", "f1.txt", "f2.txt"];
    for (i = 0; i < 3; i++){
        (function (i){
            xhr[i] = new XMLHttpRequest();
            xhr[i].open("GET", files[i], true);
            xhr[i].onreadystatechange = function () {
                if (xhr[i].readyState == 4 && xhr[i].status == 200) {
                   //do stuff
                }
            };
            xhr[i].send();
        })(i);
    }
})();

};
Comments