Progo
Progo

Reputation: 3490

How to load an array of files using Ajax?

using pure JavaScript/Ajax, I would like to take an array of file names(like: ["Data.txt", "UserInfo.txt", "Project.txt"]), and then load their data into an array.

The code would look like this:

var fileNames = ["Data.txt", "UserInfo.txt", "Project.txt"],
    fileData = [],
    client = new XMLHttpRequest();
client.onreadystatechange = function() {
    if (client.readyState === 4) {
        fileData.push(client.responseText);
    };
};
for(i = 0; i < fileNames.length; i++){
    client.open('GET', fileNames[i]);
    client.send();
};
console.log(fileData);

. And that is what I tried to do, but it didn't work correctly.

How can I achieve this?

Thank you.

Upvotes: 1

Views: 235

Answers (1)

Edgar Alexander
Edgar Alexander

Reputation: 374

You're making asynchronous requests, this is how it should be for synchronous requests:

var fileNames = ["Data.txt", "UserInfo.txt", "Project.txt"],
    fileData = [],
    client = new XMLHttpRequest();

for(i = 0; i < fileNames.length; i++){
    client.open('GET', fileNames[i], false);
    client.send();
    fileData.push(client.responseText);
};
console.log(fileData);

Upvotes: 1

Related Questions