2015-02-23 75 views
0

我有這個問題,一個Ajax調用:承諾的回調函數,並在同一個函數

我的用戶谷歌recapcha,我有一個服務器端的加載JS數據。我使用recapcha的方式是

<script src="https://www.google.com/recaptcha/api.js?onload=onScriptLoaded&render=explicit"></script> 

這意味着我等待這個功能onScriptLoaded然後手動渲染capchas。

我還包括本我的頭標籤內

<script type="text/javascript" src="/profile/js"></script> 

其返回類似

userData = {}; 
userData.id = 1; 
userData.name = 'koko'; 

現在這是好的,但我所試圖做的是某種「promisses?」 ,basiccaly我要尋找一個語法像

$.when(onScriptLoaded, $.getScript("/profile/js")).done(function(a1, a2) { 
    console.log(arguments); 
}); 

,所以我可以進入我的回調函數,裝載等..然後初始化我JS類(因爲我使用這些回調的值)

在這種情況下,但是我得到一個錯誤

Uncaught ReferenceError: onScriptLoaded is not defined 

因爲我havnen't解釋什麼是「onScriptLoaded」是。

所以..是有辦法使這種語法的工作在我的情況

謝謝!

+0

功能'onScriptLoaded'應該在全球範圍內 – 2015-02-23 13:17:42

+0

是的,但是,我怎麼能宣稱它的方式,該功能將等待谷歌API的回調,然後才能執行 – Izopi4a 2015-02-23 13:19:44

回答

1

你可以嘗試像

//a promise that will be resolved once the googe captcha code is executed 
var captchaPromise; 
(function() { 
    var deferred = jQuery.Deferred(); 
    //the onload callback for google captcha 
    window.onScriptLoaded = function (data) { 
     console.log('looks like the captcha is complered now', arguments); 
     //once the captcha callback is invoked resolve the deferred 
     deferred.resolve(data); 
    } 
    captchaPromise = deferred.promise(); 
})(); 

//use the when method with the captch promise and ajax promise 
$.when(captchaPromise, $.getScript("/profile/js")).done(function (a1, a2) { 
    console.log('when callback'); 
    console.log(arguments); 
}); 

演示:Fiddle

+0

它的作品完美無瑕,我無法搜索。延遲對象我不太好。 – Izopi4a 2015-02-23 13:33:21