ajax方法XHR.readyState五種狀態與示例


 

 

<!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)

0:請求未初始化,還沒有調用 open()。

1:請求已經建立,但是還沒有發送,還沒有調用 send()。

2:請求已發送,正在處理中(通常現在可以從響應中獲取內容頭)。

3:請求在處理中;通常響應中已有部分數據可用了,沒有全部完成。

4:響應已完成;您可以獲取並使用服務器的響應了。


免責聲明!

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



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