玩轉ajax,轉ajax
1.什麼是ajax?
Ajax 是 Asynchronous JavaScript and XML(以及 DHTML 等)的縮寫。
2.ajax需要什麼基礎?
HTML 用於建立 Web 表單並確定應用程式其他部分使用的欄位。
JavaScript 代碼是運行 Ajax 應用程式的核心代碼,協助改進與伺服器應用程式的通訊。
3.Ajax的請求步驟
3.1 建立一個對象XMLHttpRequest對象
3.2設定回調onreadystatechange方法
判斷成功 status=200 readyStates = 4
3.3 設定open
第一個參數 GET或者POST
第二個參數 Url
第三個參數 true(非同步) false(同步)
3.4 發送請求send方法 GET形式send方法沒有參數
POST形式send方法有參數 參數的形式 鍵=值&鍵=值
3.5 POST請求 需要設定hdader
setRequestHeader("Content-Type","application/x-www-form-urlencoded");
4.html代碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>ajax</title> 6 </head> 7 <body> 8 <h1>Ajax請求</h1> 9 <hr>10 <button onclick='sendAjax()'>sendAjax</button>11 <script>12 function sendAjax(){13 //建立一個xhr對象14 if(window.XMLHttpRequest){15 var xhr = new XMLHttpRequest();16 }17 else {18 var xhr = new ActiveXObject('Microsoft.XMLHTTP');19 }20 console.log('initital',xhr.readyState);21 // 當狀態發送改變 回調這個函數22 xhr.onreadystatechange = function(){23 console.log(xhr.readyState);24 if(xhr.readyState==4 && xhr.status==200){25 // 輸出響應的文字物件26 console.log(xhr.responseText);27 }28 }29 //發送請求30 xhr.open('GET','01.php',true);31 // xhr.open('GET','01.php',false);32 // xhr.open('GET','01.php');33 console.log("open",xhr.readyState);34 35 xhr.send();//非同步請求 在這時間點 分線程走36 console.log('send',xhr.readyState)37 }38 </script>39 </body>40 </html>View Code
5.php代碼
<?php // sleep(5); echo "hellow world"; ?>
6.點擊F12或者Ctrl+shift+I檢查元素,然後觸發點擊事件,看到的