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);
    }
})
相关推荐
bearpping6 小时前
Nginx 配置:alias 和 root 的区别
前端·javascript·nginx
@大迁世界7 小时前
07.React 中的 createRoot 方法是什么?它具体如何运作?
前端·javascript·react.js·前端框架·ecmascript
颜酱8 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
霍理迪8 小时前
Vue的响应式和生命周期
前端·javascript·vue.js
竹林81811 小时前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js
Kel13 小时前
深入剖析 openai-node 源码:一个工业级 TypeScript SDK 的架构之美
javascript·人工智能·架构
SuperEugene14 小时前
Vue3 模板语法规范实战:v-if/v-for 不混用 + 表达式精简,避坑指南|Vue 组件与模板规范篇
开发语言·前端·javascript·vue.js·前端框架
Luna-player14 小时前
Vue 3 + Vue Router 的路由配置,简单示例
前端·javascript·vue.js