微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax 封装

1. js 封装

      function ajax(opt) {
        // option
        opt = opt || {};
        opt.url = opt.url || ‘‘;
        opt.data = opt.data || null;
        opt.success = opt.success || function () {};
        opt.method = (function (method) {
          if (method) {
            return method.toupperCase() == ‘GET‘ ? ‘GET‘ : ‘POST‘;
          };
          return ‘GET‘;
        }(opt.method));
        opt.async = (function (async) {
          return (!async ||async +‘‘ == ‘false‘) ? false : true;
        }(opt.async));

        // xhr
        var xmlHttp = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(‘Microsoft.XMLHTTP‘);
        var postData = (function (data) {
          var params = [];
          for (var key in data) {
            params.push(key + ‘=‘ + data[key]);
          }
          return params.join(‘&‘);
        }(opt.data));

        if (opt.method === ‘POST‘) {
          xmlHttp.open(opt.method,opt.url,opt.async);
          xmlHttp.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded;charset=utf-8‘);
          xmlHttp.send(postData);
        } else if (opt.method === ‘GET‘) {
          xmlHttp.open(opt.method,opt.url + ‘?t=‘ + Math.random() + ‘&‘ + postData,opt.async);
          xmlHttp.send(null);
        }

        // handle work in async=true
        xmlHttp.onreadystatechange = function () {
          if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {  // readyState  0-4   status 200 / 404
            opt.success(xmlHttp.responseText);  // 少用: responseXML    获得 XML 形式的响应数据。
          }
        };

      }

      ajax({
        method: ‘get‘,url: ‘http://localhost:3000/addMan‘,async: true,data: {
          name1: ‘value1‘,name2: ‘value2‘
        },success: function (response) {
          console.log(response);
        }
      });
      console.log(‘hello‘);

 

 

2. jq 封装

    $(document).ajaxStart(function () {

    }).ajaxError(function () {

    }).ajaxComplete(function (event,xhr,options) {
      // console.log(xhr.status);
    });

    //关闭AJAX相应的缓存 
    $.ajaxSetup({
      cache: false,beforeSend: function (xhr) {
        // xhr.setRequestHeader("Token",$.cookie("TOKEN"));
      }
    });


    window.myAjax = {
      get: function (settings) {
        doAjax("GET",settings);
      },post: function (settings) {
        doAjax("POST",settings);
      }
    }

    function doAjax(action,settings) {
      var data = settings.data;
      var url = settings.url || settings.uri;
      url = url.replace(/\{\s*\w+\s*\}/g,function (match) {
        return match;
      });
      var type = action == "GET" ? action : "POST";
      var cache = settings.cache;
      if (!cache) {
        cache = false;
      }
      var async_tag = true;
      if (settings.async != undefined || settings.async != null) {
        async_tag = settings.async;
      }
      var beforeSend;
      if (settings.beforeSend) {
        beforeSend = function (xhr) {
          // xhr.setRequestHeader("Token",$.cookie("TOKEN"));
          return settings.beforeSend();
        }
      } else {
        beforeSend = settings.beforeSend;
      }

      $.ajax({
        url: url,data: data,cache: cache,async: async_tag,type: type,timeout: 10000,beforeSend: beforeSend,success: function (result) {
          settings.success(result);
        },error: function (xhr,status,error) {

        }
      });

    }

    myAjax.post({
      url: ‘http://localhost:3000/addMan‘,success: function (data) {
        console.log(data);
      }
    });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐