1. 程式人生 > 其它 >AJAX---原生AJAX傳送GET請求

AJAX---原生AJAX傳送GET請求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX GET 請求</title>
    <style>
        #result{
            width:200px;
            height:100px;
            border:solid 1px #90b;
        }
    
</style> </head> <body> <button>點擊發送請求</button> <div id="result"></div> <script> //獲取button元素 const btn = document.getElementsByTagName('button')[0]; const result = document.getElementById("result"); //繫結事件 btn.onclick = function
(){ //1. 建立物件 const xhr = new XMLHttpRequest(); //2. 初始化 設定請求方法和 url xhr.open('GET', 'http://127.0.0.1:8000/server'); //3. 傳送 xhr.send(); //4. 事件繫結 處理服務端返回的結果 // on when 當....時候 // readystate 是 xhr 物件中的屬性, 表示狀態 0 1 2 3 4
// change 改變 xhr.onreadystatechange = function(){ //判斷 (服務端返回了所有的結果) if(xhr.readyState === 4){ //判斷響應狀態碼 200 404 403 401 500 // 2xx 成功 if(xhr.status >= 200 && xhr.status < 300){ //處理結果 行 頭 空行 體 //響應 // console.log(xhr.status);//狀態碼 // console.log(xhr.statusText);//狀態字串 // console.log(xhr.getAllResponseHeaders());//所有響應頭 // console.log(xhr.response);//響應體 //設定 result 的文字 result.innerHTML = xhr.response; }else{ } } } } </script> </body> </html>