How Can I Store An AJAX Call's Data In A Variable?
Possible Duplicate: Can’t use returned data in .ajax method of jQuery anywhere but the function itself I'm trying to store an AJAX call's return value into a variable. var get
Solution 1:
How about
var getJSONData = function(callback){
JSONData = $.getJSON('/api', callback);
};
var reloadPage = function(json_data){
//Do some DOM manipulation with the JSON data
//console.log(json_data) returns undefined
};
getJSONData(reloadPage);
Solution 2:
AJAX stands for Asynchronous JavaScript and XML. Your data is not immediately available at the moment you execute an AJAX call, so that's why you need to use callback functions to react to the later response.
jQuery AJAX calls provides Deferred Objects that you can use.
var getJSONData = function(){
return $.getJSON('/api');
};
var reloadPage = function(data){
console.log(data);
};
getJSONData().done(reloadPage);
Solution 3:
$.getJSON
doesn't return the JSON but a promise.
The simplest is to use it like this :
$.getJSON('/api', reloadPage);
Your reloadPage
function will be called with the JSON data as argument when the response will be received by the browser.
Solution 4:
$.getJSON()
is asynchronuous. It is accessible via a callback:
var getJSONData = function(callback){
$.getJSON('/api').success(data) {
callback(data);
};
};
var reloadPage = function(){
getJSONData(function(json_data) {
//Do some DOM manipulation with the JSON data
//console.log(json_data) returns undefined
});
};
reloadPage();
Post a Comment for "How Can I Store An AJAX Call's Data In A Variable?"