jQuery: Loading ajax URL as variable?
In the past I've always used the callback function in the getJson function to handle the fetched data, but as I want to save the fetched data as a variable, to prevent it from being fetched again, I've run in to some strange issues. When trying the following code out, I start getting this error in firebug; Permission denied for <http://localhost> to get property XMLHttpRequest.channel
Am I doing it wrong trying to do this without the callback function?
function fetch(){
开发者_如何学JAVA var returndata = $.getJSON( 'http://localhost/api/get/1' );
formatDataset(returndata);
}
function formatDataset(data){
var row = '';
$.each(data, function(){
row += this.name + '<br>';
});
$('#myDiv').html(row);
}
this is wrong in your code
var returndata = $.getJSON( 'http://localhost/api/get/1' );
ajax is asyncronous call , so it will start the process and goes on , you can not use that as a return type.
if you want to get things done , write the code in the succcess handler oof getjson
Yeah, you're correct in your question where you ask about the callback. The $.getJSON function returns the XMLHttpRequest not the data. So try something like:
var returndata;
function fetch(){
if (!returndata) {
$.getJSON( 'http://localhost/api/get/1', function(data) {
returndata = data;
formatDataset(returndata);
});
return;
}
formatDataset(returndata);
}
精彩评论