2012-05-22 86 views
0

我想返回x || $不用彷徨。换句话说,如果x为真,则返回x,否则执行GET调用并返回服务器提供的值。返回本地变量或GET结果

我的尝试在下面列出(理想情况下,它会遵循返回x || y格式,可能使用匿名函数而不是if/then)。

问题是我从我的$ .get函数返回似乎不是我所期望的。

希望能够解释发生了什么。

感谢

$(function(){ 

    function test(x,y) { 
    if(x==true) {return true;} 
    else{ 
     //test.php is echo($_GET['y']==123); 
     $.get('ajax.php',{'y':y},function (status) {return status;}); 
    } 
    } 

    alert(test(false,123)); 

}); 
+2

'$ .get',像所有的AJAX默认调用,是*异步* - 立即返回给调用者,不会阻塞并等待结果。您需要重构您的'test'函数以接收回调,并在您通过ajax接收到该值时调用该回调函数。 – DCoder

+0

是否可以这样完成,如果x为真,ajax调用永远不会执行? – user1032531

+0

是的,只需立即启动回调,而不是在'$ .get'中使用它。 – apsillers

回答

2

如果你正在使用jQuery 1.5或更高版本,DeferredPromise是你的朋友对这种事情。任何时候你调用AJAX调用你回来的是Promise对象,你可以通过.done(),.fail()和.then()附加函数。

但是!正如延迟/承诺和所有这些优秀介绍(http://www.erichynds.com/jquery/using-deferreds-in-jquery/)所指出的那样,您还可以使用$ .wait()处理一个不是承诺自动执行缓存的值。所以像这样的代码:

$.when(getToken()).done(
    function (token) { 
    // do something with the token, which may or may not have been 
    // retrieved from the remote service 
    } 
); 

可以处理越来越无论是缓存值回或者也没有问题的承诺:

function getToken() { 
    // Return either the cached value or a jQuery Promise. If $.when() gets the 
    // cached value it will immediately realize that you didn't give it a 
    // promise and it will instead create a jQuery Deferred to return and 
    // .resolve() it using the value it did get. Thus, either way what 
    // comes out of the function is something .when() can deal with and call a function. 
    if (this.cache["token"]) { 
    return this.cache["token"]; 
    } else { 
    return $.get(" ... some url ... "); 
    } 
}; 
+0

没有详细看过它,但会。坚信这是正确的答案。谢谢 – user1032531