jquery 简单封装ajax,每次请求自动携带token

1.ajax.js

var HttpRequest = function (options) {
  var defaults = {
    type: 'get',
    headers: {},
    data: {},
    dataType: 'json',
    async: true,
    cache: false,
    beforeSend: null,
    success: null,
    complete: null
  };
  var o = $.extend({}, defaults, options);
  $.ajax({
    url: o.url,
    type: o.type,
    headers: {
      'Content-Type': o.contentType,
      'access_token': o.token
    },
    data: o.data,
    dataType: o.dataType,
    async: o.async,
    beforeSend: function () {
      o.beforeSend && o.beforeSend();
    },
    success: function (res) {
      o.success && o.success(res);
    },
    complete: function () {
      o.complete && o.complete();
    }
  });
};

var loginHttp = function (options) {
  // 登入页无需携带token
  // 后台如果要求 Content-Type 
  if (options.type == 'post') {
    options.contentType = 'application/x-www-form-urlencoded';
  }
  HttpRequest(options);
}
var ajaxHttp = function (options) {
  if (options.type == 'post') {
    options.contentType = 'application/x-www-form-urlencoded';
  }
  // 每次请求携带token
  options.token = localStorage.getItem('access_token');
  HttpRequest(options);
}

2.简单使用
1)url使用的都是mock上的线上地址,看效果直接全部代码复制到本地看效果


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Documenttitle>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js">script>
  <script src="./ajax.js">script>
head>
<body>
  <button class="submit">登入button>
  <button class="request">登入之后请求button>
  <script>
    $('.submit').click(function () {
      loginHttp({
        url: 'https://www.easy-mock.com/mock/5c6f93e1cfe7502fd386d993/xinyou/login',
        type: 'post',
        data: {},
        beforeSend: function () { // 可选
          // loading 显示
        },
        success: function (res) {
          console.log(res);
          // 本地存入token
          localStorage.setItem('access_token',res['access_token']);
        },
        complete: function () { // 可选
          // loading 关闭
        }
      })
    })
    $('.request').click(function () {
      ajaxHttp({
        url:'https://www.easy-mock.com/mock/5c6f93e1cfe7502fd386d993/xinyou/banner',
        type: 'get', 
        data: {}, 
        beforeSend: function () { 
          // loading 显示
        },
        success: function (res) {
          console.log(res);
        },
        complete: function () {
          // loading 关闭
        }
      })
    })
  script>
body>
html>

你可能感兴趣的:(JQuery,javaScript)