第一个 Ajax 入门实例

来源:互联网 发布:淘宝买东西后退款bug 编辑:程序博客网 时间:2024/04/17 07:08

http://blog.csdn.net/liruxing1715/article/details/7104404


  1. <html>  
  2.     <head>  
  3.         <title>Ajax</title>  
  4.         <script language="javascript">  
  5.             var xmlHttp; // 定义一个全局变量 xmlHttp  
  6.               
  7.             // 创建 XMLHttpRequest 对象  
  8.             function createXMLHttpRequest() {  
  9.                 if (window.ActiveXObject) {  
  10.                     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE  
  11.                 } else if (window.XMLHttpRequest) {  
  12.                     xmlHttp = new XMLHttpRequest(); // XMLHttpRequest  
  13.                 }  
  14.             }  
  15.               
  16.             function startRequest() {  
  17.                 createXMLHttpRequest(); // 创建 XMLHttpRequest  
  18.                 var url = 'index.php?' + new Date().getTime();  // 异步传输到的页面 index.php,后面加 new Date().getTime(),是为了消除 IE 的缓存  
  19.                 xmlHttp.open('GET', url, true);  // open() 方法发送一个异步请求  
  20.                 // 属性变化了就会触发 onreadystatechange 事件  
  21.                 xmlHttp.onreadystatechange = function() {  
  22.                     // 如果请求的状态等于4(接受成功),并且服务器返回的 HTTP 响应值为200(请求成功)  
  23.                     if (xmlHttp.readyState==4 && xmlHttp.status==200) {  
  24.                         // 弹出服务器返回的文本  
  25.                         alert('服务器返回:' + xmlHttp.responseText);  
  26.                     }  
  27.                 }  
  28.                 xmlHttp.send(null);  
  29.             }  
  30.         </script>  
  31.     </head>  
  32.     <body>  
  33.         <input type="button" value="异步通讯" onClick="startRequest();" />  
  34.      </body>  
  35. </html>  

index.php

[php] view plaincopy
  1. <?php  
  2.     header('Content-type:text/html;Charset=GB2312');  
  3.     echo '异步测试成功!';  
  4. ?>  

0 0
原创粉丝点击