存储 $.getJSON() 响应到本地变量

Storing $.getJSON() response to local var

本文关键字:变量 响应 getJSON 存储      更新时间:2023-09-26

我需要多次使用一个函数,并希望避免一遍又一遍地编写相同的方法。我想使用 $.getJSON() 响应并将其存储在将返回的变量中。这样我就可以调用该方法。

function startFilter(){
            var grid = [];
            $.getJSON('data/gridData1.json',function(json){
                grid = json;
                console.log(grid);
            });
            console.log(grid);
            return grid;
        }

网格变量在 .getJSON 内部设置,但不在 .getJSON 外部设置。 任何想法为什么,如果需要更多信息,请告诉我?

Ajax 调用是异步的。这是事物在时间中的定位方式。

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)
}

您应该使用回调来构建逻辑:

function startFilter(callback) {
    $.getJSON('data/gridData1.json', callback);
}
var grid = [];
startFilter(function(json) {
    grid = json;
    // your logic here
});
var grid;
function startFilter(dataReady ){
        var grid = [];
        $.getJSON('data/gridData1.json',function(json){
            grid = json;
             dataReady () ; 
        });
        console.log(grid);
        return grid;
    }
startFilter ( function () {
console.log(grid);
} ) ;