Ajax---錯誤處理


http狀態碼:
1、網絡暢通,服務器端能接收到請求,服務器返回的結果不是預期結果。
可以判斷服務器端返回的狀態碼,分別進行處理。xhr.status獲取http狀態碼

2、網絡暢通,服務器端沒有接收到請求,返回404狀態碼
檢查請求地址是否錯誤。

3、網絡暢通,服務器端能接收請求,服務器端返回500狀態碼。
服務器端錯誤,找后端程序員進行溝通。

4、網絡中斷,請求無法發送到服務器端。
會觸發xhr對象下面的onerror事件,在onerror事件處理函數中對錯誤進行處理。

Ajax狀態碼:表示Ajax請求的過程狀態碼,ajax對象返回的
Http狀態碼:表示請求的處理結果 是服務器端返回的

ajax錯誤處理

.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>07Ajax錯誤處理.html</title>
 6 </head>
 7 <body>
 8     <button id='btn'>發送Ajax請求</button>
 9     <script type="text/javascript">
10         var btn=document.getElementById('btn'); 11         btn.onclick=function(){ 12             var xhr=new XMLHttpRequest(); 13             xhr.open('get','http://localhost:3000/error'); 14  xhr.send(); 15             xhr.onload=function(){ 16                 //xhr.status 獲取http狀態碼
17  console.log(xhr.responseText) 18                 if(xhr.status==400){ 19                     alert("請求出錯!") 20  } 21  } 22             xhr.onerror=function(){ 23                 alert('網絡中斷,無法發送Ajax請求') 24  } 25  } 26     </script>
27 </body>
28 </html>

app.js

app.get('/error',(req,res)=>{ res.status(400).send('not ok'); })

有網情況:

 無網情況:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM