Reputation: 5942
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.
Upvotes: 3
Views: 199
Reputation: 2322
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.
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'xml',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
The examples of implantation of the above method is:
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
You might want to something like:
function readData() {
var returnData;
xhr_get('data.xml').done(function(data) {
returnData = data;
});
return returnData;
}
Hope that helps.
Upvotes: 1