从getJSON调用的函数中获取返回值
如果$.getJSON()
成功获取JSON数据,则调用一个函数,如下所示。 如何捕获返回的值output
?
$.getJSON(url, function(data) { // Do stuff with data if succeeds in getting the data return output; } );
由于您希望在回调结束时调用另一个函数,因此您应该在回调本身中执行此操作。 它是异步调用的,结果不在下一行。 所以:
$.getJSON(url, function(data) { // Do stuff with data if succeeds in getting the data $.getJSON(data, function() { .. }); } );
因为回调是异步调用的,所以无法处理回调之外的返回值。
相反,在回调内部,您需要通过将其写入给定或 – 喘息来处理“返回值”! – 全局变量。 🙂
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
var outsideVar; $.getJSON(url, function(data) { // Do stuff with data if succeeds in getting the data outsideVar = data; } );
这样您就可以将输出写入“global”变量outsideVar(因为它在外部声明),因此您可以从任何您想要的地方访问它。