一个简单的XMLHttpRequest响应。与xml交互

页面helloAjax.htm

 1 
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 5 <script type="text/javascript">
 6 var xmlhttp;
 7 //创建一个XmlHttpRequest,
 8 function CreateXmlHttpRequest()
 9 {
10     if(window.ActiveXObject)//为IE ?
11       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//ActiveXObject对象
12     else if(window.XMLHttpRequest)
13       xmlhttp= new XMLHttpRequest();//javascript对象
14 }
15 
16 function StartRequest()
17 {
18     CreateXmlHttpRequest();
19     
20     xmlhttp.onreadystatechange=StateChange;//状态改变时执行的函数
21     xmlhttp.open("POST","test.xml",true);//与服务器进行响应.get方式,连接的是一个跟这个页面同目录的xml,异步方式
22     xmlhttp.send(null);//
23 }
24 function StateChange()
25 {
26 
27     if(xmlhttp.readyState==4)
28     {
29         if(xmlhttp.status==200)
30         {
31             alert(xmlhttp.responseText);
32         }
33     }
34 }
35 </script>
36 
37 <title>XMLHttpRequest Test</title>
38 </head>
39 <body>
40 
41     <input type="button" value="开始一个请求" onClick="StartRequest();" />
42 
43 
44 </body>
45 </html>
46 
test.xml 只有一行内容
Hello World!


注意,两个文件必须防止在服务器上面响应,否则 if(xmlhttp.status==200) 不会成立。xmlhttp.status会一直为0 。
posted @ 2009-07-26 06:45  Sum_yang  阅读(202)  评论(0编辑  收藏  举报