programing

Ajax 쿼리 포스트 오류를 포착하려면 어떻게 해야 하나요?

nicescript 2023. 3. 14. 23:30
반응형

Ajax 쿼리 포스트 오류를 포착하려면 어떻게 해야 하나요?

Ajax 요청이 실패했을 경우 오류를 파악하여 적절한 메시지를 보여주고 싶습니다.

제 코드는 다음과 같습니다만, 실패한 Ajax 요청을 잡을 수 없었습니다.

function getAjaxData(id)
{
     $.post("status.ajax.php", {deviceId : id}, function(data){

        var tab1;

        if (data.length>0) {
            tab1 = data;
        }
        else {
            tab1 = "Error in Ajax";
        }

        return tab1;
    });
}

Ajax 요청이 실패했을 때 "Error in Ajax"가 실행되지 않는다는 것을 알게 되었습니다.

Ajax 오류를 처리하고 실패 시 적절한 메시지를 표시하려면 어떻게 해야 합니까?

jQuery 1.5에서는 지연 객체 메커니즘을 사용할 수 있습니다.

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });

또 다른 방법은.ajax:

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});

jQuery 1.5는 이를 적절하게 처리하는 지연 개체를 추가했습니다.전화만 하면 됩니다.$.post통화 후에 원하는 핸들러를 첨부합니다.지연 오브젝트를 사용하면 성공 핸들러와 오류 핸들러를 여러 개 연결할 수도 있습니다.

예:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

jQuery 1.8보다 이전 버전에서는done호출되었다success그리고.fail호출되었다error.

$.ajax({
  type: 'POST',
  url: 'status.ajax.php',
  data: {
     deviceId: id
  },
  success: function(data){
     // your code from above
  },
  error: function(xhr, textStatus, error){
      console.log(xhr.statusText);
      console.log(textStatus);
      console.log(error);
  }
});
$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });

간단한 방법은 ajaxError를 구현하는 것입니다.

Ajax 요청이 오류와 함께 완료될 때마다 jQuery는 ajaxError 이벤트를 트리거합니다.이 시점에서 .ajaxError() 메서드로 등록된 모든 핸들러가 실행됩니다.

예를 들어 다음과 같습니다.

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});

는 ajaxError 문서를 읽을 것을 권장합니다.위에서 설명한 단순한 사용 사례보다 더 많은 작업을 수행합니다. 주로 콜백에는 다음과 같은 다양한 매개 변수가 포함됩니다.

$('.log').ajaxError(function(e, xhr, settings, exception) {
  if (settings.url == 'ajax/missing.html') {
    $(this).text('Triggered ajaxError handler.');
  }
});

응답을 기록해야 합니다.텍스트:

$.ajax({
    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
  }
})
.done(
 function (data) {
  //your code
 }
)
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );
})

.done()비교하여 미묘한 차이가 있는 .then()을 사용하는 경우:

return $.post(url, payload)
.then(
    function (result, textStatus, jqXHR) {
        return result;
    },
    function (jqXHR, textStatus, errorThrown) {
        return console.error(errorThrown);
    });

.onerror 핸들러를 ajax 객체에 첨부하면, 왜 사람들은 vanila가 플랫폼 간에 작업할 때 응답을 위해 JQuery를 게시해야 하는지...

Quickie 예:

ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
    alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );

언급URL : https://stackoverflow.com/questions/2833951/how-do-i-catch-an-ajax-query-post-error

반응형