521源码-免费源码下载-免费学习教程-常见的原生js封装ajax

更多 网站源码 学习教程 游戏源码,请点击👉-521源码-👈获取最新资源

请看以下案例:

复制代码
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);
    }
})
相关推荐
yuguo.im15 小时前
Chrome DevTools Performance 是优化前端性能的瑞士军刀
前端·javascript·性能优化·chrome devtools
FSHOW17 小时前
【独立开发日记】MQ端到端类型安全
前端·javascript·后端
阿华的代码王国18 小时前
【Android】OkHttp发起GET请求 && POST请求
android·java·okhttp·网络连接
chxii18 小时前
7.2elementplus的表单布局与模式
javascript·vue.js·elementui
Js_cold18 小时前
Notepad++使用技巧1
前端·javascript·fpga开发·notepad++
dreams_dream19 小时前
vue中的与,或,非
前端·javascript·vue.js
柳杉19 小时前
使用three.js搭建3d隧道监测-3
前端·javascript·three.js
lggirls21 小时前
特殊符号在Html中的代码及常用标签格式的记录
前端·javascript·html
deepdata_cn1 天前
基于JavaScript的智能合约平台(Agoric)
javascript·区块链·智能合约
webKity1 天前
React 的基本概念介绍
javascript·react.js