0

所以我在理解传递 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) 我得到一个对象,这就是我想要的。那么我可以使用一些Content.theContent。虽然当 jsonData 返回到 someFunction 并且我 console.log(someContent) 我得到未定义。我不明白,我认为这将是一个对象,就像它在 getJSON 函数中一样。

4

2 回答 2

4

getJSON is called asynchronously, so you are not getting what you expect.

Let me explain:

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

You need:

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

    });
}

Here is how you pass arguments to a callback JavaScript: Passing parameters to a callback function

For your function it will be:

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

});
}
于 2013-04-30T21:32:26.683 回答
2

This is beacause $.getJSON is asynchronous. So, when getFooterContent() returns, at that point the JSON data hasn't been retrieved yet, hence the undefined.

What you should instead do is have getFooterContent() return a promise object.

function getFooterContent() {
    var promise = $.getJSON("url");
    return promise;
}

function someFunction() {
    var promise = getFooterContent();
    var outsideCopy;

    promise
    .done(function(data) {
        outsideCopy = data;
        console.log(outsideCopy);
    })
    .fail(function(e) {
        console.log('Error');
        console.log(e);
    });
}

The above example can be shortened by removing the variable declarations. I left them in so the code is easier to understand

于 2013-04-30T21:31:51.367 回答