JQuery: обрабатывать ошибки в getJSON()?
Как обрабатывать 500 ошибок при использовании jQuery getJSON?
Было несколько вопросов об обработке ошибок с помощью getJSON()
and JSONP, но я не работаю с JSONP, просто обычным JSON.
Другой ответ предлагает использовать .ajaxSetup()
перед вызовом getJSON()
, поэтому я попробовал это:
$.ajaxSetup({
"error":function() {
alert('Error!');
}});
$.getJSON('/book_results/', function(data) { # etc
Но я обнаружил, что предупреждение всегда срабатывает, даже когда результат корректно сформирован.
Любые идеи?
Ответы
Ответ 1
Метод getJSON
не возвращает исходные ошибки, но вы можете погрузиться в объект xhr, который возвращается как параметр в обратном вызове.
Метод getJSON
является сокращенной функцией для jQuery.ajax
. Используя jQuery.ajax
, вы можете легко справиться с ошибкой:
$.ajax({
url: 'http://127.0.0.1/path/application.json',
dataType: 'json',
success: function( data ) {
alert( "SUCCESS: " + data );
},
error: function( data ) {
alert( "ERROR: " + data );
}
});
Ответ 2
Если вы используете jquery версии 1.5 или выше, вы можете использовать новые методы .success(function),.error(function) и .complete(function)
Пример из http://api.jquery.com/jQuery.get/
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get("example.php", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
Прекрасно подходит для меня. Надеюсь, это поможет
Ответ 3
вы можете увидеть его на jquery api getJSON: http://api.jquery.com/jQuery.getJSON/
$.getJSON(url).done(function(data){
$("#content").append(data.info);
})
.fail(function(jqxhr){
alert(jqxhr.responseText);
});
// jquery1.5 +
обратный вызов сбоя будет срабатывать, когда текст не является правильной строкой json или другими отказоустойчивыми решениями
Ответ 4
Использование jQuery 3.2.1:
$.getJSON('/api/feed/update', function (data) {
console.log(data);
}).catch(function (jqXHR, textStatus, errorThrown) {
console.error(jqXHR);
console.error(textStatus);
console.error(errorThrown);
});
Ответ 5
Пожалуйста, сделайте следующее. Код Pseduo:
$.getJSON('/path/to_your_url.do?dispatch=toggle&' + new Date().getTime(), function(data, status, xhr){
if( xhr.status == 200 )
// all good and do your processing with 'data' parameter( your response)
else {
//error - check out the values for only in chrome for 'console'
console.log(xhr.status);
console.log(xhr.response);
console.log(xhr.responseText)
console.log(xhr.statusText);
}
}