gpt4 book ai didi

javascript - JSON 数据和函数

转载 作者:行者123 更新时间:2023-11-28 12:36:40 25 4
gpt4 key购买 nike

所以我在理解传递 JSON 数据时遇到了困难。

function getFooterContent(){
//ajax call to get json file
$.getJSON("scripts/pageData/footer/footerData.json", function(jsonData){
console.log(jsonData);
return jsonData;
}).fail(function(){
console.log("fail");
return -1;
});

//Return the json file
}

function someFunction(){
var someContent = new Object();
someContent = getFooterContent();
console.log(someContent);
}

所以现在我正在调用一个 JSON 文件。当我 console.log(jsonData) 时,我得到一个对象,这就是我想要的。那么我就可以 someContent.theContent。尽管当 jsonData 返回到 someFunction 和 console.log(someContent) 时,我得到了未定义。我不明白,我以为它会是一个像 getJSON 函数中的对象。

最佳答案

getJSON 是异步调用的,因此您没有得到您期望的结果。

让我解释一下:

function getFooterContent(){
//ajax call to get json file
$.getJSON("scripts/pageData/footer/footerData.json",
function(jsonData){ // This function is executed when request is ready and server responds with OK
console.log(jsonData);
return jsonData;
}).

fail(function(){ // This when servers responds with error
console.log("fail");
return -1;
});

//Return the json file
// You are returning undefined actually
}

function someFunction(){
var someContent = new Object();
someContent = getFooterContent();
console.log(someContent);
}

您需要:

function someFunction(){
var someContent = new Object();
getFooterContent(function(someContent){
// someContent is passed by getFooterContent
console.log(someContent);

});
}

以下是如何将参数传递给回调JavaScript: Passing parameters to a callback function

对于您的功能来说,它将是:

function getFooterContent(done, fail){
$.getJSON("scripts/pageData/footer/footerData.json",
function(jsonData){ // This function is executed when request is ready and server responds with OK
// console.log(jsonData);
// return jsonData;
done.call(null, jsonData); // or done.apply()
}).

fail(function(){ // This when servers responds with error
// console.log("fail");
// return -1;
fail.call(); // or fail.apply()

});
}

关于javascript - JSON 数据和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com