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

Maw*_*awg 25 jquery

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

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/

Dav*_*ard 54

你是对的,你可以使用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
});
Run Code Online (Sandbox Code Playgroud)

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

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

我更喜欢前者保持代码不那么纠结,但两者都是等价的.

  • jQuery现在使用.done和.fail而不是.success和.error,它们都已被弃用但可能会工作一段时间.http://api.jquery.com/jQuery.get/ (7认同)

Pek*_*ica 15

.get()只是.ajax()预先设定了许多选项的同义词.使用ajax()得到全方位的选项,包括error回调.

$.ajax({
type: "GET",
url: "test.htm",
error: function(xhr, statusText) { alert("Error: "+statusText); },
success: function(msg){ alert( "Success: " + msg ); }
}
);
Run Code Online (Sandbox Code Playgroud)


sta*_*One 11

截至jQuery 3.0 .success()并且.error()已经过折旧.
你可以使用.done().fail()不是

$.get( url )
    .done(function( data, textStatus, jqXHR ) {
        console.log(data);
    })
    .fail(function( jqXHR, textStatus, errorThrown ) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown );
    });
Run Code Online (Sandbox Code Playgroud)

资料来源:https://api.jquery.com/jQuery.ajax/