本文介绍了存储$ .getJSON()响应本地var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要多次使用一个函数,并希望避免一遍又一遍地编写相同的方法。我想使用$ .getJSON()响应并将其存储在将要返回的var中。这样我就可以调用方法。
I need to use a function several times and wanted to avoid writing the same method over and over. I wanted to use $.getJSON() response and store it in a var that will be returned. That way I can just call the method.
function startFilter(){
var grid = [];
$.getJSON('data/gridData1.json',function(json){
grid = json;
console.log(grid);
});
console.log(grid);
return grid;
}
网格var设置在.getJSON内但不在.getJSON之外。任何想法为什么,如果需要更多信息让我知道?
the grid var is set inside of the .getJSON but not outside of .getJSON. any ideas why, and if more info is needed let me know?
推荐答案
Ajax调用是异步的。以下是事物在当时的定位方式。
The Ajax calls are async. Here is how the things are positioned in the time.
function startFilter(){
var grid = []; // (1)
$.getJSON('data/gridData1.json', function(json){ // (2)
grid = json; // (5)
console.log(grid); // (6)
});
console.log(grid); // (3)
return grid; // (4)
}
您应该使用回调来构建逻辑:
You should use callbacks to build your logic:
function startFilter(callback) {
$.getJSON('data/gridData1.json', callback);
}
var grid = [];
startFilter(function(json) {
grid = json;
// your logic here
});
这篇关于存储$ .getJSON()响应本地var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!