2、url不带参数通过接口调用数据,带参数就是url链接后面跟着?name=小明&sex=男的类似参数

这里是封装的

 1 function ajax(url,fnSucc,fnFaild){  //参数1地址  参数2成功与否  参数3失败
 2     var oAjax = null;
 3       // 创建ajax对象
 4     if(window.XMLHttpRequest){ 
 5         oAjax = new XMLHttpRequest();
 6     }else{
 7         oAjax = new ActiveXObject("Microsoft.XMLHTTP"); 
 8     }
 9      // 连接服务器 open() 有两个参数 open(方法(post,get),url,是否是异步)
10         oAjax.open('GET',url,true);  
11           // 发送请求       
12         oAjax.send();  
13         // 服务器接收并返回      
14         oAjax.onreadystatechange=function(){
15             if(oAjax.readyState==4){
16                     var time = new Date().getTime();  //加入时间戳以清理缓存 
17                 if(oAjax.status==200){ //状态码
18                     fnSucc(oAjax.responseText+time);  Ajax请求成功后的内容就被存放在responseText(返回以文本形式存放的内容)这个属性下面
19                 }else
20               {
21                  if(fnFaild){
22                     fnFaild();
23                  }
24               }
25            }               
26   }
27 }

这里是调用

 btn.onclick=function(){
           // 封装插件
                ajax('test.txt',function(str){ //成功状体
                     alert(str);
                  },function(){ //失败状态
                    alert('木有');
                  });

               
         } 

 

posted @ 2016-11-22 10:13  Model-Zachary  阅读(277)  评论(0编辑  收藏  举报