如何检测JQuery $.get失败?寻求简单的代码示例

我是一个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/

解决方法

您可以使用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,errorThrown) { });

我更喜欢前者保持代码较少纠结,但两者都是等效的。

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...