因为getJSON方法是异步的。这是怎么回事...
getInviteLink : function() { // this function is called...
var me = this,
invite_url; // happens right away
$.getJSON('get_invite_code.json', function(data) {
// Step 2, these statements don't happen until later
// -- when the response is received
console.log(data.invite_url); // this
invite_url = data.invite_url;
}); // Step 1. the getJSON is called right away
console.log(invite_url) // this happens right after the
// the getJSON is called, but before
// it gets a response. Thus no data when the log
// statement is invoked
return invite_url; // also no data (yet) when this return statement
// is executed
},
添加要解决你的软件,你需要认识到,你不能做的事情invite_url
从服务器接收到的JSON响应之后,直到。 - 如果您的客户端出现网络问题或服务器问题,可能永远不会收到。
您可以将函数传递给您的getJSON调用。该函数将使用invite_url。同时,您可以为您的客户做其他事情。
如果你的软件没有任何东西可以做,直到你得到响应,然后设置一个忙指标(一个旋转的圆圈或者其他东西),然后启动json请求并且当你得到响应时让函数取消忙指标背部。
有关更多信息,请参阅jQuery json文档。
建议修改? Inser成功的回报? – AnApprentice 2012-07-08 02:21:32
对不起,但你不能返回值。你不能建立一个同步函数,它返回异步请求的值。您可以做的最好的方法是使用成功回调中的值。 – 2012-07-08 02:22:33