原生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

猜你喜欢

转载自www.cnblogs.com/t-young1201/p/10229645.html