当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 原生js---ajax的封装插件.js---(对get和post做了兼容)

原生js---ajax的封装插件.js---(对get和post做了兼容)

2018年11月15日  | 移动技术网IT编程  | 我要评论
function ajax(method,url,data,fn){
    // 1、创建对象
    var xhr=null;
    try{
    xhr=new xmlhttprequest();
    }catch(e){
    xhr=new activexobject("microsoft.xmlhttp");
    }
    
    // 2、open方法
    if(method=="get"&&data){
      url=url+"?"+data;
    }
    xhr.open(method,url,true);
    
    // 3、send方法
    if(method=="get"){
        xhr.send()
    }else{
    // post请求时执行
    // 声明发送的数据类型
        xhr.setrequestheader('content-type','application/x-www-form-urlencoded');
        xhr.send(data);
    }
    
    // 4、接收数据
    xhr.onreadystatechange=function(){
        if(xhr.readystate==4){
            if (xhr.status==200) {
            // 数据接收成功后执行传来的函数
            fn(xhr.responsetext)
            }else{
            alert("错误"+xhr.status)
            }
        }
    }
}



注:function ajax(method,url,data,fn){}
method----方法
url---路径
data---数据,不用传数据时,函数传该参数""
fn---数据接收成功后执行传来的函数

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网