处理jQuery.getScript中的错误

psy*_*tik 7 javascript ajax jquery

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

回调获取data/textStatus的文档似乎不正确 - 回调得不到.

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

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

som*_*som 31

从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());
    }
})
Run Code Online (Sandbox Code Playgroud)

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

  • 如果脚本是跨域url(`always`回调或全局`ajaxError`处理程序),则`fail`回调似乎不起作用. (15认同)
  • `fail`回调适用于jQuery 2.0+中的跨域URL (4认同)

Sal*_*n A 17

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

  1. 创建一个错误处理程序,并在几秒钟后使用将其设置为触发 handle = window.setTimeout
  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);
});
Run Code Online (Sandbox Code Playgroud)


小智 6

全局JQuery Ajax-ErrorHandler将起作用!

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

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

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


cll*_*pse -1

这有点黑客,但是..

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

script_test.js:

var script_test = true;
Run Code Online (Sandbox Code Playgroud)

进而:

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

或者,您可以尝试看看脚本中的内容是否确实存在——函数、变量、对象等。


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

main_script.js:

function scriptLoaded(scriptName)
{
    alert(scriptName + " loaded!");
}

$.getScript("script_test.js");
Run Code Online (Sandbox Code Playgroud)

script_test.js:

(function ()
{
    scriptLoaded("script_test.js");
})();
Run Code Online (Sandbox Code Playgroud)