簡體   English   中英

嘗試捕獲JavaScript時未觸發Http狀態

[英]Http status not triggering on try and catch javascript

我具有將JSON發布到可以正常工作的API端點的功能。 這是我的代碼。

function sendValuesPageLoad(){
     var xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function () {
        try {
          if (xhr.readyState === 4 && xhr.status === 200) {}
        } catch (ex) {
            alert('Error parsing response.');
        }
     }
     try {
        xhr.open("POST", "test.html?"+encodedString, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send();
     } catch (ex) {
        xhr.open("POST", "error.html?"+encodedString, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send();
     }
} 

我要實現的目標是,如果xhr.status不等於200,則執行進一步的操作。

但是捕獲並沒有被觸發。

有人可以幫忙嗎?

提前致謝。

XMLHttpRequest帶有自己的錯誤處理程序onerror 更新您的示例

function sendValuesPageLoad(){
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
       if (xhr.status === 200) {
          // successful
       } else {
          // fails
          throw new Error('Failed with status: ' + xhr.statusText);
       }
    }
    xhr.onerror = function () {
       throw new Error('There is a problem');
    }
    xhr.open("POST", "test.html?"+encodedString, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send();
}

您可以通過將其包裝在Promise並捕獲任何錯誤來改善此問題

function sendValuesPageLoad(){
  return new Promise(function(resolve, reject) { 
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
       if (xhr.status === 200) {
          // successful
          resolve(xhr.response);
       } else {
          // fails
          reject(xhr.statusText);
       }
    }
    xhr.onerror = function () {
       reject(Error("Network Error"));
    }
    xhr.open("POST", "test.html?"+encodedString, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send();
  }
}

// use case
sendValuesPageLoad().then(function(response) { 
   // use your response here
}).catch(function(error) {
   // handle your error
});

 function sendValuesPageLoad(){ var encodedString = "value=2"; var xhr = new XMLHttpRequest(); console.log('UNSENT: ', xhr.status); xhr.open("POST", "test.html?" + encodedString, true); console.log('OPENED: ', xhr.status); xhr.onprogress = function () { console.log('LOADING: ', xhr.status); }; xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = function () { console.log('DONE: ', xhr.status); if(xhr.status === 200){ alert("Status code is 200"); }else{ alert("Status code is not 200, but " + xhr.status); xhr.open("POST", "error.html?"+encodedString, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(); } }; xhr.send(); } sendValuesPageLoad(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM