Jquery Ajax 오류 처리가 중단됨을 무시합니다.
ajax 호출에 대한 전역 오류 처리 방법을 원합니다. 이것이 현재 가지고있는 것입니다.
$.ajaxSetup({
error: function (XMLHttpRequest, textStatus, errorThrown) {
displayError();
}
});
의 오류를 무시해야합니다 aborted
. errorThrown
이 null이고 textStatus
입니다 error
. 어떻게 확인 aborted
합니까?
오늘도 동일한 사용 사례를 처리해야했습니다. 내가 작업중인 앱에는 1) 사용자가 멀리 이동하거나 2) 일종의 일시적인 연결 / 서버 오류로 인해 중단 될 수있는 이러한 장기 실행 아약스 호출이 있습니다. 오류 처리기가 연결 / 서버 실패에 대해서만 실행되고 사용자가 멀리 이동하지 않기를 원합니다.
먼저 Alastair Pitts의 대답을 시도했지만 중단 된 요청과 연결 실패가 모두 상태 코드와 readyState를 0으로 설정했기 때문에 작동하지 않았습니다. 다음으로 sieppl의 대답을 시도했습니다. 두 경우 모두 응답이 없으므로 헤더가 없기 때문에 작동하지 않았습니다.
나를 위해 일한 유일한 해결책은 페이지가 언로드되었음을 나타내는 전역 변수를 설정하는 window.onbeforeunload에 대한 리스너를 설정하는 것입니다. 그런 다음 오류 처리기는 페이지가 언로드되지 않은 경우에만 오류 처리기를 확인하고 호출 할 수 있습니다.
var globalVars = {unloaded:false};
$(window).bind('beforeunload', function(){
globalVars.unloaded = true;
});
...
$.ajax({
error: function(jqXHR,status,error){
if (globalVars.unloaded)
return;
}
});
최신 jQuery에서는 다음 request.statusText
과 같은지 확인할 수 있습니다 'abort'
.
error: function (request, textStatus, errorThrown) {
if (request.statusText =='abort') {
return;
}
}
내가 찾은 것은 중단 된 요청이있을 때 status
and / or readyState
equal 0
.
내 전역 오류 처리기에서 메서드 맨 위에 확인이 있습니다.
$(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError) {
//If either of these are true, then it's not a true error and we don't care
if (jqXHR.status === 0 || jqXHR.readyState === 0) {
return;
}
//Do Stuff Here
});
나는 이것이 나를 위해 완벽하게 작동한다는 것을 알았습니다. 이것이 당신이나 이것에 부딪히는 다른 사람에게 도움이되기를 바랍니다 :)
오류 함수에 전달 된 textStatus 인수를보고 싶을 것입니다. http://api.jquery.com/jQuery.ajax/ 에 따르면 "success", "notmodified", "error", "timeout", "abort"또는 "parsererror"값을 사용할 수 있습니다. "중단"은 분명히 확인하려는 것입니다.
여기에 더 긴 메모 : jquery-gotcha-error-callback-triggered-on-xhr-abort
bluecollarcoders 응답은 자바 스크립트에 의해 중단 된 ajax 요청에 대해 작동하지 않기 때문에 다음은 내 솔루션입니다.
var unloaded = false;
...
$(window).bind('beforeunload', function(){
unloaded = true;
});
$(document).ajaxError(function(event, request, settings) {
if (unloaded || request.statusText == "abort") {
return;
}
...
}
예 :
handler = jQuery.get("foo")
handler.abort()
이제 ajaxError 핸들러에서 무시됩니다.
Alastair Pitts'a 답변을 바탕으로 더 많은 정보를 제공하기 위해 이렇게 할 수도 있습니다.
$(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError)
{
{
if (jqXHR.status === 0)
{
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404)
{
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500)
{
alert('Internal Server Error [500].');
} else if (exception === 'parsererror')
{
alert('Requested JSON parse failed.');
} else if (exception === 'timeout')
{
alert('Time out error.');
} else if (exception === 'abort')
{
alert('Ajax request aborted.');
} else
{
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
if (!jqXHR.getAllResponseHeaders()) {
return;
}
});
I had the same issue here, and what I did as solution was to set an "aborting" var just before the call of abort(), as below:
aborting = true;
myAjax.abort();
and only show the error on the error handler of the ajax request, if abort isn't true.
$.ajax({
[..]
error: function() {
if ( !aborting ) {
// do some stuff..
}
aborting = false;
}
});
The quick (and dirty) solution:
if (status === 0) { // or -1 depending on where you do this
setTimeout(function() {
// error handling here
}, 2000); // 2 seconds, or use more ...
}
if the xhr error status is 0 (*) set a delay of 2 seconds around error handling code, by that time the browser has already loaded the new page context and the error will never show.
If the error was not due to an abort by navigating to another page the error will show with some delay.
*NOTE: depending on the used libs and which error handler you use it may be -1 instead of zero (Angular ...) or something else entirely.
IMPORTANT: the status text may vary from one browser to another and used libs so IMHO you cannot rely on it, please let me know in the comments if you find a cross-browser solution
If you abort the ajax request manually, you can do like this:
var xhr;
function queryData () {
if (xhr) {
// tag it's been aborted
xhr.hasAborted = true;
// manually canceled request
xhr.abort();
}
xhr = $.ajax({
url: '...',
error: function () {
if (!xhr.hasAborted) {
console.log('Internal Server Error!');
}
},
complete: function () {
xhr = null;
}
});
}
참고URL : https://stackoverflow.com/questions/4807572/jquery-ajax-error-handling-to-ignore-aborted
'Nice programing' 카테고리의 다른 글
Swift : 사용자 정의 ViewController 이니셜 라이저 (0) | 2020.10.14 |
---|---|
Python 디버거, pdb 시작하기 (0) | 2020.10.14 |
객체 PHP의 모든 속성을 반복 (0) | 2020.10.14 |
strpos에서 배열을 바늘로 사용 (0) | 2020.10.13 |
C #에서 잘못된 XML 문자 이스케이프 (0) | 2020.10.13 |