기본 콘텐츠로 건너뛰기

[jquery ajax] how to set error callback function for $.get

source:

question:

answer:

source: http://stackoverflow.com/questions/5047906/how-to-detect-jquery-get-failure-seeking-simple-code-example

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

.get() is just a synonym for .ajax() with a number of options pre-set. Use ajax() to get the full range of options, including the error callback.
$.ajax({
type: "GET",
url: "test.htm",
error: function(xhr, statusText) { alert("Error: "+statusText); },
success: function(msg){ alert( "Success: " + msg ); }
}
);

source: http://stackoverflow.com/questions/4062317/jquery-get-error-response-function

Note that with the new jqXHR object in jQuery 1.5, you can set an error handler after calling $.get:
$.get('http://example.com/page/2/', function(data){ 
    $(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
    alert('woops'); // or whatever
});
source: http://api.jquery.com/jQuery.get/#jqxhr-object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});


On the other hand,

source: http://api.jquery.com/jquery.ajax/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});

댓글