如何检测JQuery $ .get失败?寻求简单的代码示例 [英] How to detect JQuery $.get failure? Seeking simple code example

查看:473
本文介绍了如何检测JQuery $ .get失败?寻求简单的代码示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JQuery n00b.我正在尝试使用$ .get()编写一个非常简单的代码. 官方文档

I'm a JQuery n00b. I'm trying to code a very simple using $.get(). The official documentation says

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等,并为用户制定有意义的错误消息.

So, if all goes well, my callback function for success will be called. However, if the request fails, I would like to get the HTTP code :404, 502, etc and formulate a meaningful error message for the user.

但是,由于这是一个异步调用,所以我可以想象我可能有几个出色的人. .ajaxError()如何知道它对应于哪个请求?也许最好使用jQuery.get()返回的jqXHR对象的.error()方法?

However, since this is an asynchronous call I can imagine that I might have several outstanding. How would .ajaxError() know which request it corresponds to? Maybe it would be better to use the .error() method of the jqXHR object returned by jQuery.get()?

有人可以提供一个非常简单的代码示例吗?也许成功例程调用Alert(找到页面"),而失败例程检查404,并执行Alert(找不到页面")

Can someone please provide an extremely simple code example? Perhaps the success routine calls Alert("Page found") and the failure routine checks for 404 and does an Alert("Page not found")

更新:以下页面非常有帮助... http://api.jquery.com /jQuery.get/

Update: the following page is extremely helpful ... http://api.jquery.com/jQuery.get/

推荐答案

您是对的,您可以使用jQuery 1.5的新jqXHR将错误处理程序分配给$.get()请求.这是您可以做到的方式:

You're right that you can use jQuery 1.5's new jqXHR to assign error handlers to $.get() requests. This is how you can do it:

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
});

您还可以将处理程序直接链接到调用上:

You can also chain handlers directly onto the call:

$.get('/path/to/resource.ext')
     .success(function(result) { })
     .error(function(jqXHR, textStatus, errorThrown) { });

我更希望前者使代码不那么混乱,但是两者是等效的.

I prefer the former to keep the code less tangled, but both are equivalent.

这篇关于如何检测JQuery $ .get失败?寻求简单的代码示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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