I have the following code that outputs the initialized value of my variable before it is updated by an $.ajax() callback. It seems that the 'get' is performed after the variable is logged despite how the code is written. How can I correct this? Thanks for any suggestions.
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false,
error: function()
{
},
success: function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
//console.log(statusUpdate.numQueries);
}
});
} // end getNumQueries
};
statusUpdate.getNumQueries();
console.log(statusUpdate.numQueries)
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false,
error: function()
{
},
success: function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
console.log(statusUpdate.numQueries);
}
});
} // end getNumQueries
};
Uncomment the logger in the success callback. Otherwise the log may run before the ajax call gets a chance to complete.
Ajax calls are asynchronous. I'm guessing that you are seeing 0
in your console?
Put the console.log
inside the success function. But I'd recommend passing a callback or returning the promise object (it will require you to restructure your JavaScript).
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false,
error: function()
{
},
success: function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
console.log(statusUpdate.numQueries)
}
});
} // end getNumQueries
};
statusUpdate.getNumQueries();
UPDATE : Here's what I meant by using a promise. For more info, see Deferred Object and the jQuery.ajax() documentation
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
var deferred = new $.Deferred();
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false
}).done(function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
deferred.resolve();
).fail(function () {
deferred.reject();
});
return deferred.promise();
} // end getNumQueries
};
statusUpdate.getNumQueries().done(function () {
console.log(statusUpdate.numQueries)
});
Ok, I guess I can't make it work as envisioned. I added a complete function but it seems like kind of a workaround. Is this a reasonable practice? Thanks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.