在jQuery.getScript处理错误 [英] Handling errors in jQuery.getScript

查看:1254
本文介绍了在jQuery.getScript处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery的 getScript加入的功能似乎不支持一个错误回调函数。我不能使用全球ajax的错误处理code在这里,当地的误差函数将是理想的。

jQuery's getScript function doesn't seem to support an error callback function. I can't use the global ajax error handling code here, a local error function would be ideal.

文件回调中获取数据/ textStatus似乎不正确 - 回调得既不

Documentation that the callback gets data/textStatus seems incorrect - the callback gets neither.

我如何检测调用getScript加入失败(服务器不可用,例如)有什么建议?

Any suggestions on how I detect that a call to getScript failed (server not available, for instance)?

编辑:只是看着源,它似乎是回调时才会激活成功,数据始终设置为null,textStatus没有定义的(因为它是一个成功的,只是回调,我presume)。该文档是非常不正确的此功能。

Just looked at source, and it seems like the callback is only invoked on success, with data always set to null and textStatus not defined (since it's a success-only callback, I presume). The documentation is very incorrect for this function.

推荐答案

这是一个黑客位,但..

This is a bit of a hack, but..

您可以宣布脚本里面的变量加载,并检查它已加载脚本(假定完成功能还是触发)后:

You could declare a variable inside the scripts you load and check for it after you've loaded a script (assuming that the complete-function still fires):

script_test.js:

script_test.js:

var script_test = true;

然后:

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

或者你可以试试,看看无论是在脚本中,确实存在 - 函数,变量,对象等。


一个更通用的方法,这样做会增加你要加载的脚本里面自动执行的功能,使它们在你的主脚本执行函数:

Or you could just try and see if whatever is in your script, actually exists--functions, variables, objects, etc.


A more generic way to do this would be adding a self-executing function inside the scripts you want to load, and make them execute a function in your "main" script:

main_script.js:

main_script.js:

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

$.getScript("script_test.js");

script_test.js:

script_test.js:

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

这篇关于在jQuery.getScript处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆