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);
    }
})
相关推荐
看到请催我学习23 分钟前
内存缓存和硬盘缓存
开发语言·前端·javascript·vue.js·缓存·ecmascript
XiaoYu20022 小时前
22.JS高级-ES6之Symbol类型与Set、Map数据结构
前端·javascript·代码规范
儒雅的烤地瓜2 小时前
JS | JS中判断数组的6种方法,你知道几个?
javascript·instanceof·判断数组·数组方法·isarray·isprototypeof
道爷我悟了2 小时前
Vue入门-指令学习-v-on
javascript·vue.js·学习
27669582922 小时前
京东e卡滑块 分析
java·javascript·python·node.js·go·滑块·京东
golitter.2 小时前
Ajax和axios简单用法
前端·ajax·okhttp
PleaSure乐事2 小时前
【Node.js】内置模块FileSystem的保姆级入门讲解
javascript·node.js·es6·filesystem
雷特IT3 小时前
Uncaught TypeError: 0 is not a function的解决方法
前端·javascript
awonw3 小时前
[前端][easyui]easyui select 默认值
前端·javascript·easyui
老齐谈电商3 小时前
Electron桌面应用打包现有的vue项目
javascript·vue.js·electron