AJAX---處理網路超時和網路異常
阿新 • • 發佈:2021-10-09
const btn = document.getElementsByTagName('button')[0]; const result = document.querySelector('#result'); btn.addEventListener('click', function(){ const xhr = new XMLHttpRequest(); //超時設定 2s 設定 xhr.timeout = 2000; //超時回撥 處理網路超時 xhr.ontimeout = function(){ alert("網路異常, 請稍後重試!!"); } //網路異常回調 處理網路異常 xhr.onerror = function(){ alert("你的網路似乎出了一些問題!"); } xhr.open("GET",'http://127.0.0.1:8000/delay'); xhr.send(); xhr.onreadystatechange = function(){if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status< 300){ result.innerHTML = xhr.response; } } } })