ITPub博客

首页 > IT职业 > IT职场 > 原生js---ajax的封装插件.js---(对get和post做了兼

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

IT职场 作者:airland 时间:2021-09-09 09:59:14 0 删除 编辑
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---数据接收成功后执行传来的函数


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/964/viewspace-2814592/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    96
  • 访问量
    11394