gpt4 book ai didi

jQuery ajax 错误处理 "script"dataType

转载 作者:行者123 更新时间:2023-11-30 23:45:22 25 4
gpt4 key购买 nike

我正在使用 jQuery 的 AJAX 函数的包装函数,如下所示:

$.getAjax = function(url, type, callback){
$.ajax({
url: url,
cache: false,
dataType: type,

success: function(){
alert("success");
},
complete: function(XMLHttpRequest, textStatus){
alert("complete");

if (callback != undefined) {
callback();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("error");
}
});
}

当我使用“text”作为数据类型时,即使 url 无效,它也能完美工作。当 url 无效时,它首先调用错误,然后调用完整函数。没关系。但是,当我使用“script”作为数据类型时,当 url 无效时它不会调用任何内容。当我使用“script”作为数据类型时,我应该如何捕获 HTTP 404 错误和其他错误?

最佳答案

我查看了 jQuery 的源代码,发现它没有调用任何错误处理程序方法。事实上,只有当http get请求成功时,它才会调用success()和complete()函数。

// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
script.src = s.url;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}

// Handle Script loading
if ( !jsonp ) {
var done = false;

// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
success();
complete();

// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
}

// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );

// We handle everything using the script element injection
return undefined;
}

关于jQuery ajax 错误处理 "script"dataType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3364096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com