封装原生ajax方法

function ajaxFun(type,data,url,success){//type 请求类型 data 携带参数 url 请求地址 success 回调方法
  var xhr = new XMLHttpRequest();
  if(type == "get"){
    if(data){
      url+='?';
      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          url+=data[key]+"&";
        };
      };
      url = url.substring(0,url.length-1);
    };
    xhr.open(type,url);
    xhr.send();
  }else if(type == "post"){
    xhr.open(type,url);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    if(data) {
      xhr.send(data);
    }else{
      xhr.send();
    };
  };
  xhr.onreadystatechange=function(){
    if(xhr.readyState==4 && xhr.status==200){
      success(xhr);
    };
  };
}
posted @ 2020-12-25 23:33  虹猫淘气  阅读(177)  评论(0编辑  收藏  举报