无法从jQuery函数返回JSON对象

时间:2019-09-16 16:51:48

标签: javascript jquery ajax

我无法从在页面加载时运行的函数中正确返回(或也许“捕获”是一个更好的术语)JSON对象。我想捕获该对象,以便随后可以通过用户操作将其发布到另一个页面。

我正在Windows 10(最新版的Firefox)上运行它。

var configJson;
$(document).ready(function () { // Wait till page is loaded
    configJson = getConfig();
    console.log("Outside: " + JSON.stringify(configJson)); // DEBUG
});

function getConfig() {
    var jqxhr = $.getJSON("/config/", function () {
        //console.log("Success."); // DEBUG
    })
        .done(function (data) {
            console.log("Inside: " + JSON.stringify(data)); // DEBUG
            return data;
        })
        .fail(function () {
            console.log("Fail."); // DEBUG
            return JSON.parse("{}");
        })
}

在控制台中,返回“外部”,在函数中看到“内部”:

Inside: {"name":"fred"}
Outside: undefined

1 个答案:

答案 0 :(得分:2)

您不能从异步函数返回数据,因此您将需要使用回调。像这样:

$(document).ready(function () {
    getConfig(function(configJson) {
        console.log("Outside: " + JSON.stringify(configJson));
        // do something with configJson here.
    });
});

function getConfig(callback) {
    var jqxhr = $.getJSON("/config/")
        .done(function (data) {
            console.log("Inside: " + JSON.stringify(data));
            callback(data);
        })
        .fail(function () {
            console.log("Failed!");
            callback({});
        });
}

如果您需要一个包含配置的全局变量,则可以执行以下操作:

var globalConfig = {};
$(document).ready(function () {
    getConfig(function(configJson) {
        globalConfig = configJson;
    });
});
// ...