1

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.

2
  • What is this fileData.push = client.responseText? Doesn't look right. Also, if I'm not wrong, this looks like everyday ajax problem. When you log fileData the files are not returned by the response yet. Commented Jan 23, 2014 at 1:35
  • @elclanrs Thanks for pointing that out, I have fixed the first part but I am not sure what to do about the second part. Thank again... :) Commented Jan 23, 2014 at 1:46

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean by asynchronous and synchronous requests? What is the difference? Thanks.
Well, your solution does work! I would still like to know the answer to my previous comment… :)
Asynchronous requests are executed in a different thread of the application, with this process the main program doesn't have to wait for an instruction to be completed in order to execute the next code, what happened here was that all the requests where overwrited by each iteration and the previous where aborted, only the last one could make it, when you do a synchronous request the program will have to wait until a requested page gets downloaded for execute the next instruction. As you can see, we don't use any callback like readystatechange in the new model, just the loop.

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.