2013-10-25 46 views
0

我試圖讓jQuery.when函數工作。jQuery.when函數,在ajax調用完成後無法獲取值

我有一個功能測試,即連接到另一個腳本,並檢索名字值。

這工作,我可以看到的價值,如果我做的console.log

但我似乎無法使可用的值在.done功能

任何想法,爲什麼?

function test (email, key) { 

     if (!isEmpty(email) && !isEmpty(key)) { 

      var script = getScriptUrl(email, key); 

      return jQuery.ajax({ 
         url : script, 
         dataType: 'script', 
         success : function() { 
          // This function retrieves the fisrtname value 
          firstName = getScriptUrlFunction('FirstName'); 
         } 
        }); 
     } 
    } 



$.when(

    test(email, key) 

).done(function(aa1) { 

    // This shows undefined - how do I get the firstName here? 
    // Why doesn't it work? 

    console.log(aa1); 

}); 

這裏是AA1的控制檯:

[undefined, "success", Object { readyState=4, status=200, statusText="success", more...}] 

有沒有辦法從AA1得到名字價值?基本上把它傳遞給aa1

Ty!

+0

你確定'的isEmpty(電子郵件)&&的isEmpty(鍵)'是真的!?爲什麼你的dataType腳本?你真的要求另一個JavaScript文件,並期待它返回一個值嗎? –

+0

我得到該腳本後,firstName = getScriptUrlFunction('FirstName'); --- getScriptUrlfunction返回名字值 –

+0

'firstName'是全局的,只是訪問它。 –

回答

1

您需要使用.then()鏈接,而不是success回調:

return $.ajax({ ... }) 
    .then(function() { return getFirstName(...); });