怎樣設置請求超時時間和超時監聽函數


1. 設置請求超時時間: xhr.timeout, 如果超時, 請求會自動終止; 參數是毫秒;

2. 設置請求超時監聽函數: xhr.ontimeout, 如果請求超時, 則會觸發ontimeout事件的監聽函數;

var xhr = new XMLHttpRequest();
var url = '/server';

xhr.ontimeout = function () {
  console.error('The request for ' + url + ' timed out.');
};

xhr.onload = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      // 處理服務器返回的數據
    } else {
      console.error(xhr.statusText);
    }
  }
};

xhr.open('GET', url, true);
// 指定 10 秒鍾超時
xhr.timeout = 10 * 1000;
xhr.send(null);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM