AJAX之超时与网络异常处理

<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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章