原生JS發送AJAX請求

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <meta http-http-equiv="content-type" content="text/html;charset=utf-8">
 5     <title></title>
 6   </head>
 7   <body>
 8     <script>
 9       //1 建立XMLHttpRequest對象
10       //* 絕大多數瀏覽器都支持XMLHttpRequest對象 ie低版本不支持,用ActiveXObject
11       if (window.XMLHttpRequest) {
12         var xmlhttp=new XMLHttpRequest();
13       } else {
14         var xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
15       }
16       // 2 發送請求
17       // * get/post
18       //var url='http://localhost/test.php';
19       var url='./test.php';
20       xmlhttp.open('get',url,true);
21       xmlhttp.send();
22       //3 響應請求
23       xmlhttp.onreadystatechange=function(){
24         //readyState
25         // 0: 請求未初始化 1: 服務器鏈接已創建 2: 請求已接收 3: 請求處理中 4: 請求已完成,且響應已就緒
26         //status
27         // 200: "OK" | 404: 未找到頁面
28         if (xmlhttp.readyState==4 && xmlhttp.status==200) {
29           var jsonObj=eval('['+xmlhttp.responseText+']');
30           alert(jsonObj[0].name+':'+jsonObj[0].age);
31           document.getElementById('pid').innerHTML=jsonObj[0].name+':'+jsonObj[0].age;
32         }
33       }
34     </script>
35     <p id='pid'></p>
36   </body>
37 </html>
test.html
1 <?php
2   echo json_encode(
3     array(
4       'name'=>'Harry',
5       'age'=>12
6     )
7   );
8  ?>
test.php
相關文章
相關標籤/搜索