2015-02-23 50 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