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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM