programing

onload가 XMLHttpRequest의 readyState==4와 같습니까?

nicescript 2023. 2. 15. 23:08
반응형

onload가 XMLHttpRequest의 readyState==4와 같습니까?

xhr return 이벤트에 대해 혼란스럽습니다.지금 알 수 있듯이 onreadyState ==4와 onload는 크게 다르지 않습니다.그게 사실입니까?

var xhr = new XMLHttpRequest();
xhr.open("Get", url, false);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4)
    {
        /* do some thing*/
    }
};

xhr.send(null);

또는

xhr.onload = function() { /* do something */ }

이것은 거의 항상 사실이다.하지만 한 가지 중요한 차이점은,onreadystatechange이벤트 핸들러도 다음과 같이 트리거 됩니다.readyState==4의 경우onerror통상, 핸들러는 트리거 됩니다(통상은 네트워크 접속의 문제).이 경우 상태는 0이 됩니다.최신 Chrome, Firefox 및 IE에서 이러한 현상이 발생하는지 확인했습니다.

그래서 만약 당신이onerror최신 브라우저를 타겟으로 하고 있기 때문에,onreadystatechange그러나 사용해야 합니다.onload(실제 응답 및 상태 코드를 사용하여) HTTP 요구가 정상적으로 완료된 경우에만 호출이 보증됩니다.그렇지 않으면 오류가 발생했을 때 이벤트핸들러가 2개 트리거 되는 경우가 있습니다(이렇게 해서 이 특별한 경우를 경험적으로 알게 되었습니다).

여기 다른 URL을 테스트하고 이벤트의 실제 시퀀스를 볼 수 있도록 제가 작성한 Pluker 테스트 프로그램에 대한 링크가 있습니다.readyState다양한 경우에 JavaScript 앱에서 볼 수 있는 값입니다.JS 코드도 다음과 같습니다.

var xhr;
function test(url) {
    xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", function() { log(xhr, "readystatechange") });
    xhr.addEventListener("loadstart", function(ev) { log(xhr, "loadstart", ev.loaded + " of " + ev.total) });
    xhr.addEventListener("progress", function(ev) { log(xhr, "progress", ev.loaded + " of " + ev.total) });
    xhr.addEventListener("abort", function() { log(xhr, "abort") });
    xhr.addEventListener("error", function() { log(xhr, "error") });
    xhr.addEventListener("load", function() { log(xhr, "load") });
    xhr.addEventListener("timeout", function(ev) { log(xhr, "timeout", ev.loaded + " of " + ev.total) });
    xhr.addEventListener("loadend", function(ev) { log(xhr, "loadend", ev.loaded + " of " + ev.total) });
    xhr.open("GET", url);
    xhr.send();
}

function clearLog() {
    document.getElementById('log').innerHTML = '';
}

function logText(msg) {
    document.getElementById('log').innerHTML += msg + "<br/>";
}

function log(xhr, evType, info) {
    var evInfo = evType;
    if (info)
        evInfo += " - " + info ;
    evInfo += " - readyState: " + xhr.readyState + ", status: " + xhr.status;
    logText(evInfo);
}

function selected(radio) {
    document.getElementById('url').value = radio.value;
}

function testUrl() {
    clearLog();
    var url = document.getElementById('url').value;
    if (!url)
        logText("Please select or type a URL");
    else {
        logText("++ Testing URL: " + url);
        test(url);
    }
}

function abort() {
    xhr.abort();
}

같은 것이어야 합니다. onloadXMLHttpRequest 2에 추가된 반면,onreadystatechange원래 사양부터 있었습니다.

아니, 그들은 같지 않아.네트워크 에러가 발생하거나 조작이 중단되었을 경우,onload호출되지 않습니다.사실, 가장 가까운 사건은readyState === 4되지요loadend흐름은 다음과 같습니다.

     onreadystatechange
      readyState === 4
             ⇓
 onload / onerror / onabort
             ⇓
         onloadend

간단한 코드로 그들이 오류를 처리하는 방법

xhr.onload = function() {
  // same or allowed cross origin
  if (this.status == 200) {

  }
  else {} // error http status not 200
};
xhr.onerror = function() {
  //error: cross origin, bad connection
};

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (this.status == 200) {

    }
    else {} // error: cross origin, http status not 200, bad connection
  }
};

언급URL : https://stackoverflow.com/questions/9181090/is-onload-equal-to-readystate-4-in-xmlhttprequest

반응형