我是一个JQuery n00b。我正在尝试使用$ .get()编写一个非常简单的代码。 official documentation说
If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method or. As of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.get() is also available for error handling.
所以,如果一切顺利,我将调用成功的回调函数。但是,如果请求失败,我想获取HTTP代码:404,502等,并为用户制定有意义的错误消息。
然而,由于这是一个异步调用,我可以想象我可能有几个优秀。 .ajaxError()如何知道它对应哪个请求?也许最好使用jQuery.get()返回的jqXHR对象的.error()方法?
有人可以提供一个非常简单的代码示例吗?也许成功例程调用Alert(“找到页面”)和失败例程检查404并执行警报(“找不到页面”)
更新:以下页面非常有用...... http://api.jquery.com/jQuery.get/
答案 0 :(得分:53)
你是对的,你可以使用jQuery 1.5的新jqXHR为$.get()
请求分配错误处理程序。这就是你如何做到的:
var request = $.get('/path/to/resource.ext');
request.success(function(result) {
console.log(result);
});
request.error(function(jqXHR, textStatus, errorThrown) {
if (textStatus == 'timeout')
console.log('The server is not responding');
if (textStatus == 'error')
console.log(errorThrown);
// Etc
});
您还可以直接将处理程序链接到呼叫:
$.get('/path/to/resource.ext')
.success(function(result) { })
.error(function(jqXHR, textStatus, errorThrown) { });
我更喜欢前者保持代码不那么纠结,但两者都是等价的。
答案 1 :(得分:14)
.get()
只是.ajax()
的同义词,预先设置了多个选项。使用ajax()
获取所有选项,包括error
回调。
$.ajax({
type: "GET",
url: "test.htm",
error: function(xhr, statusText) { alert("Error: "+statusText); },
success: function(msg){ alert( "Success: " + msg ); }
}
);
答案 2 :(得分:8)
自jQuery 3.0起/opt/payara41/glassfish/domains/domain1/logs/* {
daily
copytruncate
rotate 3
dateext
notifempty
}
和.success()
折旧
您可以使用.error()
和.done()
代替
.fail()