Reputation: 3123
I was wondering how to extract data from a returned object via jQuery's $.get() method. IE:
function dynamicData(file){
var wantedData;
var getObj = $.get(file);
wantedData = getObj.complete(function(data){return data;});
return wantedData;
}
$(window).load(function(){
var newData = dynamicData('somefile');
alert(newData);
});
I don't want to just stick the data to some DOM as soon as it's gotten the new data.
I get an object alerted, but how do I get data inside of it? I have no idea how the object structure is at this point since newData is an object, but newData[0] is null. Is this by chance some sort of mapped object with key:value pairs? or are we not allowed to do it this way?
Upvotes: 0
Views: 623
Reputation: 17387
Since $.get() is asynchronous, you're calling your alert before the get returns any data.
A better approach would be:
function dynamicData(file,callback){
$.get(file,function(data){
callback(data);
});
}
$(window).load(function(){
dynamicData('somefile', alert);
});
which will alert(data) when it becomes available.
Upvotes: 3
Reputation: 11009
$.get requires a callback function that will receive the data as soon as it is done loading. It will not directly return the data to the calling function!
Please refer to the jQuery.get documentation for more information.
Upvotes: 3
Reputation: 944559
You can't return from an Ajax call. It's Asynchronous.
Do whatever you want to do with the data in the success callback.
See the manual for get, which has examples.
Upvotes: 7