如何将AJAX调用的数据存储在变量中? [英] How can I store an AJAX call's data in a variable?
本文介绍了如何将AJAX调用的数据存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
Can’t use returned data in .ajax method of jQuery anywhere but the function itself
我正在尝试将AJAX调用的返回值存储到变量中.
I'm trying to store an AJAX call's return value into a variable.
var getJSONData = function(){
JSONData = $.getJSON('/api');
};
var reloadPage = function(json_data){
//Do some DOM manipulation with the JSON data
//console.log(json_data) returns undefined
};
reloadPage(getJSONData());
此代码无效.但是,当我直接访问它或使用以下代码时,该api仍然有效
This code doesn't work. The api works though when I access it directly or using the following code
$.getJSON('/api', function(data){console.log(data)});
这有效,并为我获取了我想要的JSON数据.
This works and gets me the JSON data I wanted.
有什么主意我怎么做?
推荐答案
如何
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);
这篇关于如何将AJAX调用的数据存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文