2012-05-22 84 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