<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin: 0; padding: 0; } #url{ width: 1000px; height: 30px; outline: none; border: 1px solid #000; border-radius: 5px; margin-left: 10px; } #btn{ width: 90px; height: 30px; outline: none; border: 1px solid #000; border-radius: 5px; cursor: pointer; } </style> </head> <body> <div> <label for="url"> URL:<input type="text" placeholder="請輸入要檢測的URL" id="url"> </label> </div> <br> <button class="btn" id="btn">點擊測試</button> <div id="content"> </div> </body> <script> var str = '' document.getElementById('btn').onclick = function(){ var xhr = new XMLHttpRequest(); var url = document.getElementById('url').value; if (!url) { alert('請輸入URL'); return false; } // console.log(url) console.log(xhr.status, xhr.readyState) // 0,0 xhr.onreadystatechange=function(){ // console.log(xhr) if(xhr.status === 200){ console.log(xhr.status, xhr.readyState)//200,2;200,3;200,4 str += `status:${xhr.status}` if(xhr.readyState === 4){ // console.log(xhr.getAllResponseHeaders()) str += xhr.getAllResponseHeaders() + '<br/>' } } document.getElementById('content').innerHTML = str; } xhr.open("GET",url,true); console.log(xhr.status, xhr.readyState)// 0,1 xhr.send(null) } </script> </html>
XHR.readyState == 狀態(0,1,2,3,4)html
0:請求未初始化,尚未調用 open()。服務器
1:請求已經創建,可是尚未發送,尚未調用 send()。測試
2:請求已發送,正在處理中(一般如今能夠從響應中獲取內容頭)。ui
3:請求在處理中;一般響應中已有部分數據可用了,沒有所有完成。url
4:響應已完成;您能夠獲取並使用服務器的響應了。
htm