从getJSON调用的函数中获取返回值

时间:2011-07-26 17:42:17

标签: jquery json

如果$.getJSON()成功获取JSON数据,则调用一个函数,如下所示。如何捕获返回值output

$.getJSON(url, function(data) {
     // Do stuff with data if succeeds in getting the data
     return output;
     }
);

4 个答案:

答案 0 :(得分:1)

因为异步调用回调,所以无法处理回调之外的返回值。

相反,在回调中,您需要通过将其写入给定或 - 喘息来处理“返回值”! - 全局变量。 :)

答案 1 :(得分:1)

由于你想在回调完成时调用另一个函数,你应该在回调本身中这样做。它是异步调用的,结果不在下一行。所以:

$.getJSON(url, function(data) {
     // Do stuff with data if succeeds in getting the data
     $.getJSON(data, function() { .. });
  }
);

答案 2 :(得分:0)

var outsideVar;
$.getJSON(url, function(data) {
     // Do stuff with data if succeeds in getting the data
     outsideVar = data;
     }
);

这样你就可以将输出写入“global”变量outsideVar(因为它在外面声明),所以你可以从任何你想要的地方访问它。

答案 3 :(得分:0)

the results of the call will be data


   $.getJSON(url, function(data) {
         // Do stuff with data if succeeds in getting the data
         retVal(data);
         }
    );

function retVal(myVal){
    //do stuff here, result is myVal
    alert(myVal);
}

edited, last code would not work in any way whatsoever.  this one will
相关问题