加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax 封装

发布时间:2020-12-16 02:58:50 所属栏目:百科 来源:网络整理
导读: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()

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);
      }
    });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读