ajax

Ajax.js (ajax库)

 1 function ajax(url,fnSucc,fnFaild)
 2 {
 3     //创建ajax对象
 4     var oAjax=null;    
 5     if(window.XMLHttpRequest)
 6     {
 7         oAjax=new XMLHttpRequest();
 8     }
 9     else
10     {
11         oAjax=new ActiveXObject("Microsoft.XMLHTTP");
12     }
13     
14     // 连接服务器
15     oAjax.open('GET',url,true);
16 
17     //发送请求
18     oAjax.send();
19     //alert(oAjax.readyState);
20     //接受返回
21     /*
22      oAjax.readyState:
23      0:(未初始化)还没有调用open()方法
24      1:(载入)一调用send()方法。正在发生请求
25      2:(载入成功)send()方法完成,已收到全面响应内容
26      3:(解析)正在解析响应内容
27      4:(完成)客户端可以调用
28      */
29     oAjax.onreadystatechange=function()
30     {
31         if(oAjax.readyState==4)
32         {
33             if(oAjax.status==200)
34             {
35                 fnSucc(oAjax.responseText);
36             }
37             else
38             {
39                 if(fnFaild)
40                 {
41                     fnFaild();
42                 }
43             }
44         }
45     }
46 
47 }

ajax调用

 1 <!-- 
 2     ajax 调用
 3  -->
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 <script src="Ajax.js" ></script>
10 <script>
11     window.onload=function()
12     {
13         var oBtn=document.getElementById("btn")
14         oBtn.onclick=function()
15         {
16             ajax('abc.txt',function(str){
17                 alert(str);
18             },function(){
19                 alert('发生错误');
20             });
21         }
22     };
23 </script>
24 </head>
25 <body>
26 <input id="btn" type="button" value="读取"/>
27 </body>
28 </html>

 

posted @ 2014-04-21 17:23  萧凡客  阅读(214)  评论(0编辑  收藏  举报