<script>
//獲取button
const btn = document.getElementsByClassName("button")[0];
console.log(btn)
//綁定事件
btn.addEventListener("click",function(){
//創建對象
const xhr = new XMLHttpRequest();
//初始化對象
xhr.open("POST","http://localhost:8000/ie?t="+Date.now());
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//設置請求頭
xhr.setRequestHeader("name1","ddd");
//發送
xhr.send("a=3&b=4");
//設置超時
xhr.timeout=2000;
//超時回調
xhr.ontimeout=function(){
alert("你的網絡超時了")
}
//網絡異常
xhr.onerror=function(){
alert("你斷網了")
}
//事件綁定
xhr.onreadystatechange=function(){
//判斷響應
if( xhr.readyState ===4 ){
if(xhr.status >=200 && xhr.status <300){
div.innerHTML=xhr.response;
}
}
}
})
</script>
AJAX之超時與網絡異常處理
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.