I want to read the contents of a local file using JavaScript/jQuery. I understand this is often discussed, but my example is a little different because I want to return the contents after the fetch is done rather than manipulate HTML.
I don’t want to talk about security issues and local files because this code is meant to run within my own browser (Chrome, which I start with the –allow-file-access-from-files flag).
I have the following function to get the data…
function readData() {
$.ajax({
type: "GET",
url: "data.xml",
async: false, // this does not change the outcome
dataType: "xml",
success: function(xml) {
// Got the data, find entries and return them.
console.log("Returning data");
var doc = $(xml).find('entry');
// This is where most examples manipulate dom, I want to
// return the data instead
return doc;
}
});
}
Now I want to do…
var xmlDoc = readData();
// undefined, why?
and have the document in the variable. Instead I get undefined. It seems that the function returns before the file is fetched. Or maybe I have a problem with variable scope?
Does anyone know how to accomplish this? Yes, I am sure I want to use JavaScript even though I am doing this locally.
The stackoverflow answer regarding handling of $.ajax calls has a good example of a nice way this can be used. This example can be slightly modified to give you something close to what you are looking for.
The examples of implantation of the above method is:
You might want to something like:
Hope that helps.