how can I read returned object from jQuery $.get method
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 o开发者_如何学Gof mapped object with key:value pairs? or are we not allowed to do it this way?
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.
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.
$.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.
精彩评论