侧边栏壁纸

原生js封装ajax

2024年05月09日 140阅读 4评论 0点赞

这段代码有近10年历史了,猜猜我从哪搞来的

function ajax(options) {
  var xhr = null;
  var type = 'GET';
  var params = formsParams(options.data);

  if(typeof options.type != 'undefined'){
    type = options.type.toUpperCase();
  }

  //创建对象
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (typeof options.async == "undefined") {
    options.async = true;
  }

  // 处理请求成功的回调函数
  xhr.onload = function(){
    if (xhr.status >= 200 && xhr.status < 300) {
      if (typeof options.datatype == "undefined" || options.datatype == "json") {
        if(typeof options.success === 'function'){
          options.success(JSON.parse(xhr.responseText));
        }
      } else {
        if(typeof options.success === 'function'){
          options.success(xhr.responseText);
        }
      }
    } else {
      if(typeof options.error === 'function'){
        options.error(xhr.statusText);
      }
    }
  }

  // 处理请求错误的回调函数
  xhr.onerror = function() {
    if(typeof options.error === 'function'){
      options.error(xhr.statusText);
    }
  }

  // 设置请求头部
  if (options.headers) {
    for (var header in options.headers) {
      xhr.setRequestHeader(header, options.headers[header]);
    }
  }

  // 设置请求方法、URL、是否异步、发送请求
  if (type == "GET") {
    xhr.open(type, options.url + "?" + params, options.async);
    xhr.send(null);
  } else if (type == "POST") {
    xhr.open(type, options.url, options.async);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
  }

  function formsParams(data) {
    var arr = [];
    for (var prop in data) {
      arr.push(prop + "=" + data[prop]);
    }
    return arr.join("&");
  }
}

// 使用
ajax({
    url: "api.php",// 请求地址
    type: "POST",// 请求方式
    async: true,// 同步:false,异步:true,默认为true
    datatype: "json",// 返回数据的格式,"json","text",默认为json
    headers: {},// 设置请求头部,{"token": "123456"}
    data: {// post数据
        code: "s2sdd",
        link: location.href
    },
    success: function (res) {// 处理请求成功
        console.log(res);
    },
    error: function (res) {// 处理请求错误
        console.log(res);
    }
})
0

—— 评论区 ——

昵称
邮箱
网址
取消
  1. 头像
    昨日南墙
    回复

    说的真好

  2. 头像
    回复

  3. 头像
    bei
    回复

    说的好, 非常好

  4. 头像
    11
    回复

    曹曹博主,练练实战

人生倒计时
舔狗日记