Ajax怎么处理错误

    技术2025-02-03  5

    网络畅通,服务器端能接收到请求,服务器端返回的结果不是预期结果。 可以判断服务器端返回的状态码,分别进行处理。xhr.status获取http状态码网络畅通, 服务器端没有接收到请求,返回404状态码。 检查请求地址是否错误。网络畅通, 服务器端能接收到请求,服务器端返回500状态码。 找后端程序员网络中断,请求无法发送到服务器端。 会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。 //Ajax错误处理 app.get('/error',(req,res)=>{//要先改状态码再send res.status(400).send('hello'); }) var btn = document.querySelector("#btn"); btn.onclick = function(){ //创建Ajax对象 var xhr = new XMLHttpRequest; //告诉Ajax以什么方式向哪个地址发送请求 xhr.open('get','http://localhost/error'); //发送请求 xhr.send(); xhr.onload = function(){ console.log(xhr.responseText) //打印状态码 console.log(xhr.status); if(xhr.status === 400){ alert('请求出错'); } } //当网络中断会触发onerror事件 xhr.onerror = function(){ alert('网络中断') } }
    Processed: 0.009, SQL: 9