zoukankan      html  css  js  c++  java
  • $.ajax仿axios封装

    适用于对老项目维护时,用习惯的axios不能使用的情况

    基础封装: 保留 then 的回调、baseHref、method 传 post || get || etc,

    function ajax(obj) {
      var callback = $.ajax({
        url: window.baseHref + obj.url,
        type: obj.method || "post",
        data: obj.data,
        dataType: 'json',
        beforeSend: function(request) {
          request.setRequestHeader("X-CSRF-TOKEN", window.csrf);
        },
      });
      callback.then = function(res, rej) {
        res && callback.done(res);
        rej && callback.fail(rej);
        return callback;
      }
      return callback;
    }
    

      

    例子,请求成功:

    ajax({
      url: '/webbanner',
      method: 'post',
    }).then(function(res) {
      console.log(res)
    }, function(rej) {
      console.log('rej1')
    }).then(function(res) {
      console.log('res2')
    })
    
    // output
    // 请求结果
    // 'res2'
    

      

    例子,请求失败:

    ajax({
      url: '/11111111',
      method: 'post',
    }).then(function(res) {
      console.log(res)
    }, function(rej) {
      console.log('rej1')
    }).then('', function(rej) {
      console.log('rej2')
    })
    
    // output
    // 'rej1'
    // 'rej2'
    

      

  • 相关阅读:
    UNIX环境高级编程——信号说明列表
    [Fiddler]如何让Fiddler可以抓取https的请求
    [Cookie] Read Cookie and Pass in headers
    [Training Video
    [Training Video
    [Training Video
    [Training Video
    [Training Video
    [Training Video
    [Training Video
  • 原文地址:https://www.cnblogs.com/NKnife/p/8269031.html
Copyright © 2011-2022 走看看