0

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);
    }
})();

};

2 Answers 2

1

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);
    }
})();

};
Sign up to request clarification or add additional context in comments.

1 Comment

This probably would work better than my answer. I didn't put together that he may not be wanting those exact file names ;P
0

Something like this should work

// ...
    for (i = 0; i < 3; i++){
        (function (i){
            xhr[i] = new XMLHttpRequest();
            xhr[i].open('GET', i.toString() + '.txt'); // <-- this line
            xhr[i].onreadystatechange = function () {
                if (xhr[i].readyState == 4 && xhr[i].status == 200) {
// ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.