处理jQuery.getScript中的错误

jQuery的getScript函数似乎不支持错误回调函数。 我不能在这里使用全局ajaxerror handling代码,本地错误函数将是理想的。

回调获取data / textStatus的文档似乎不正确 – 回调都没有。

关于我如何检测到对getScript的调用失败的任何建议(例如服务器不可用)?

编辑:只看源,看起来回调只是在成功时调用,数据总是设置为null而textStatus没有定义(因为它是一个成功的回调,我猜)。 该function的文档非常不正确。

这有点像黑客,但..

您可以在加载的脚本中声明一个变量,并在加载脚本后检查它(假设完整函数仍然触发):

script_test.js:

var script_test = true; 

然后:

 $.getScript("script_test.js", function () { if (typeof script_test !== undefined) alert("script has been loaded!"); }); 

或者您可以尝试查看脚本中是否有任何内容,实际存在 – 函数,变量,对象等。

更通用的方法是在要加载的脚本中添加一个自执行函数,并使它们在“主”脚本中执行一个函数:

main_script.js:

 function scriptLoaded(scriptName) { alert(scriptName + " loaded!"); } $.getScript("script_test.js"); 

script_test.js:

 (function () { scriptLoaded("script_test.js"); })(); 

从jQuery 1.5开始,您可以在调用getScript时添加.fail。

 $.getScript('foo.js', function(){ //script loaded and parsed }).fail(function(){ if(arguments[0].readyState==0){ //script failed to load }else{ //script loaded but failed to parse alert(arguments[2].toString()); } }) 

http://api.jquery.com/jQuery.getScript/#handling-errors

对于跨域脚本标记,成功事件将触发,但错误事件不会触发; 无论你使用什么语法。 你可以尝试这种方法:

  1. 使用handle = window.setTimeout创建一个error handling程序并在几秒钟后将其设置为触发
  2. 在你成功的回调函数里面,使用window.clearTimeout(handle)取消超时

示例代码:

 var timeoutId; // timeout id is a global variable timeoutId = window.setTimeout(function() { alert("Error"); }, 5000); $.getScript("http://other-domain.com/script.js", function(){ window.clearTimeout(timeoutId); }); 

全局JQuery Ajax-ErrorHandler将工作!

在$ .getScript-Call之前设置Error Handler来缓存错误。

 $(document).ajaxError(function(e, xhr, settings, exception) { alert('error in: ' + settings.url + ' \n'+'error:\n' + exception ); }); 

如JQuery手册中所述: http : //api.jquery.com/ajaxError/ 。

jquery.ajax有另一种处理错误的方法

 jQuery.ajax({ type: "GET", url: 'http://www.example.com/script_test.js', dataType: "script", error: function (XMLHttpRequest, textStatus, errorThrown) { console.log('error ', errorThrown); }, success:function(){ console.log('success'); } });