原生js实现Ajax的封装

1.封装函数

function ajax(options) {
    
    
  options = options || {
    
    };
  options.type = (options.type || "GET").toUpperCase();
  options.dataType = options.dataType || "json";
  options.async=options.async|| true;
  var params = formatParams(options.data);
  var xhr;
  //第一步 - 创建
  if (window.XMLHttpRequest) {
    
              
    xhr = new XMLHttpRequest();
  } else if(window.ActiveObject) {
    
             //IE6及以下
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
  }
   
  //第三步 - 接收
  xhr.onreadystatechange = function () {
    
    
    if (xhr.readyState == 4) {
    
    
      var status = xhr.status;
      if (status >= 200 && status < 300 || status == 304) {
    
    
        options.success(xhr.responseText);
      } else {
    
    
        options.error(status);
      }
    }
  }
  
  // 第二步 -连接 和 发送
  if (options.type == "GET") {
    
    
    xhr.open("GET", options.url + "?" + params, options.async);
    xhr.send(null);
  } else if (options.type == "POST") {
    
    
    xhr.open("POST", options.url, options.async);
    //设置表单提交时的内容类型
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
  }

  //格式化参数
  //将{ user:'username', pass:'password' }格式
  //先变成【user=username,pass=password】
  //最后变成"user=username&pass=password"
  function formatParams(data) {
    
    
	 var arr = [];
	 for (var name in data) {
    
    
	   arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
	 }
	  return arr.join("&");
   }
}

2.封装函数的使用实例

 ajax({
    
    
    url:"https://server/login",
    type:'post',
    data:{
    
     user:'username', pass:'password' },
    dataType:'json',
    success:function(data){
    
    
        //发送请求成功后,对data数据进行处理,做一些其他的事情。
    },
    //异常处理
    error:function(err){
    
    
        console.log(err);
    }
})

猜你喜欢

转载自blog.csdn.net/qq_44875145/article/details/104662890