玩轉ajax

1.什麼是ajax?php

  Ajax 是 Asynchronous JavaScript and XML(以及 DHTML 等)的縮寫。html

2.ajax須要什麼基礎?ajax

  HTML 用於創建 Web 表單並肯定應用程序其餘部分使用的字段。 
     JavaScript 代碼是運行 Ajax 應用程序的核心代碼,幫助改進與服務器應用程序的通訊。服務器

3.Ajax的請求步驟app

   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代碼:ide

 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"; ?> url

 6.點擊F12或者Ctrl+shift+I檢查元素,而後觸發點擊事件,看到的效果圖spa

  

相關文章
相關標籤/搜索