我无法从在页面加载时运行的函数中正确返回(或也许“捕获”是一个更好的术语)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
答案 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;
});
});
// ...