1NetMedia_Blog

<< jQuery.extend()和jQuery.fn.ext...  类别: Ajax Js 单页面应用通过hash来路由 >>
Jquery Ajax方法改造
[ 日期: 2018-08-27 12:48:27 AM | 作者: admin | 来源: Original | 人气:661 | 晴天 | 心情: +2 ] 字号: 【
急速栏目链接:
标签:ajax  |  jquery  |  post  |  get  |  load  |  源码  |  

/**
* MyJQueryAjax,参考$.post和$.get的思路
* @Author:游于艺(QQ:58012007)
* @Advantage:url参数必须有,其他主参数(data, callback, dataType)可自行决定是否需要,顺序可变(data参数需要注意特殊处理),ajax其他不常用的属性可以写到扩展参数中(extendParam)
* @Instruction:$ajax.post = $.ajax.post(url[,……]); $ajax.load(url[,……]);方法,支持选择器,可在callback中接收返回值,一般可用作模板加载。
* @param:(url, data, callback, dataType, {extendParam,里面同名参数会覆盖主参数})--尽量按顺序
* @url:必须参数,url后直接跟扩展参数(extendParam)时,data参数必须为Null或空
* @callback:为success(data,textStatus){}方法
*
* 【extendParam常用的扩展参数如下】
* isLoading:是否显示loading,默认值true:显示,默认使用layer.jsloading效果
* loading:{open:function(){console.log("start loading!")},close:function(){console.log("close loading!")}}//自定义loading及移除loading
* contentType: 'application/json;charset=utf-8',
* xhrFields: { withCredentials: true },//跨域($.support.cors = true;)
* cache: false,
* async:true,
* beforeSend:function(xhr){},
* error:function(XMLHttpRequest, textStatus, errorThrown){},
* complete:function(XMLHttpRequest, textStatus) {}
* 更多>
*/
;(function($,undefined){
  $ajax = $.ajax;
  $.each(['get','post','delete','put','load'],function(i,method){
    $ajax[method] = function(url) {
      var args = arguments;
      if(typeof(args[0])!=='string'){
        console.log('url\u53C2\u6570\u9519\u8BEF\uFF01');
        return false;
      }
      if(args.length>1){
        var paramData;
        for(var i=1; i<args.length; i++){
          paramData = args[i];
          if((typeof(paramData)==='object'||
            (typeof(paramData)==='string'&&$.inArray(paramData,'json,xml,jsonp,script,text,html'.split(','))<0)||
            $.isArray(paramData)||
            (paramData===''||paramData===null||paramData===undefined))&&i==1){
            var data = paramData;
          }
          if($.isFunction(paramData)){
            var callBack = paramData;
          }
          if(typeof(paramData)==='string'&&$.inArray(paramData,'json,xml,jsonp,script,text,html'.split(','))>=0){
            var dataType = paramData;
          }
          if ($.isPlainObject(paramData)&&i>1) {
            var extendParam = paramData;
          }
        }
      }
      if(extendParam===undefined){
        extendParam = {};
      }
      var baseParam = {};
      if(data!==undefined&&data!==null&&data!==''){
        baseParam.data = data;
      }
      if(dataType!==undefined){
        baseParam.dataType = dataType;
      }
      if(callBack!==undefined){
        baseParam.success = callBack;
      }

      var isLoading = typeof(extendParam.isLoading)==='boolean'?extendParam.isLoading:true;
      if (isLoading||(extendParam.hasOwnProperty('loading')&&isLoading)) {
        baseParam.beforeSend = function(){
          if(extendParam.hasOwnProperty('loading')){
            extendParam.loading.open();
          }else{
            layer.load(2);//你可以使用其他loading插件或自定义
          }
        }
        if(extendParam.hasOwnProperty('complete')){
          var tmpFN = extendParam.complete;
          extendParam.complete = function(XMLHttpRequest, textStatus){
            if(extendParam.hasOwnProperty('loading')){
              extendParam.loading.close();
            }else{
              layer.closeAll('loading');
            }
            tmpFN(XMLHttpRequest, textStatus);
          }
        }else{
          extendParam.complete = function(XMLHttpRequest, textStatus){
            if(extendParam.hasOwnProperty('loading')){
              extendParam.loading.close();
            }else{
              layer.closeAll('loading');
            }
          }
        }
      }
      if(method=='load'){
        method='get';
        var selector,off = url.indexOf(" ");
        if (off>=0) {
          selector = $.trim(url.slice(off,url.length));
          url = url.slice(0,off);
        }
        baseParam.success = function(data){
          data = selector?$("<div>").append($.parseHTML(data)).find(selector).html() : data;
          callBack(data);
        }
      }
      var params = $.extend({
        url: url,
        type: method
      },baseParam,extendParam,$.isPlainObject(url)&&url);
      console.log(params);
      return $.ajax(params);
    }
  });
})(jQuery);
/**全局loading事件
*使用全局loading事件,可以把下面压缩版中loading功能块去掉;
*压缩版中:var n=true;默认开启loading,可以设为false。
*/
$(document).ajaxStart(function(){
layer.load(2);
});
$(document).ajaxStop(function(){
layer.closeAll('loading');
});
【压缩版】

;(function(a,b){$ajax=a.ajax;a.each(["get","post","delete","put","load"],function(c,d){$ajax[d]=function(f){var q=arguments;if(typeof(q[0])!=="string"){console.log("url\u53C2\u6570\u9519\u8BEF\uFF01");return false}if(q.length>1){var s;for(var n=1;n<q.length;n++){s=q[n];if((typeof(s)==="object"||(typeof(s)==="string"&&a.inArray(s,"json,xml,jsonp,script,text,html".split(","))<0)||a.isArray(s)||(s===""||s===null||s===b))&&n==1){var m=s}if(a.isFunction(s)){var h=s}if(typeof(s)==="string"&&a.inArray(s,"json,xml,jsonp,script,text,html".split(","))>=0){var r=s}if(a.isPlainObject(s)&&n>1){var j=s}}}if(j===b){j={}}var o={};if(m!==b&&m!==null&&m!==""){o.data=m}if(r!==b){o.dataType=r}if(h!==b){o.success=h}/*自定义loading功能块*/var p=typeof(j.isLoading)==="boolean"?j.isLoading:true;if(p||(j.hasOwnProperty("loading")&&p)){o.beforeSend=function(){if(j.hasOwnProperty("loading")){j.loading.open()}else{layer.load(2)}};if(j.hasOwnProperty("complete")){var e=j.complete;j.complete=function(i,t){if(j.hasOwnProperty("loading")){j.loading.close()}else{layer.closeAll("loading")}e(i,t)}}else{j.complete=function(i,t){if(j.hasOwnProperty("loading")){j.loading.close()}else{layer.closeAll("loading")}}}}/*loading功能块结束*/if(d=="load"){d="get";var k,g=f.indexOf(" ");if(g>=0){k=a.trim(f.slice(g,f.length));f=f.slice(0,g)}o.success=function(i){i=k?a("<div>").append(a.parseHTML(i)).find(k).html():i;h(i)}}var l=a.extend({url:f,type:d},o,j,a.isPlainObject(f)&&f);return a.ajax(l)}})})(jQuery);
使用示例:

$(function(){
//示例1:
  $ajax.post("test.do",
    '{"name": "uname", "age": 18}',
    'html',
    function(data){console.log('this is success callBack!')},
    {
      error:function(XMLHttpRequest, textStatus, errorThrown){
        console.log("errorThrown:"+errorThrown)
      },
      complete:function(XMLHttpRequest, textStatus){
        console.log("ajax complete!");
      },
      loading:{open:function(){console.log("【start loading!】")},close:function(){console.log("【close loading!】")}}
    })
  .done(function(){
    console.log("done")
  });
//示例2:
  $.ajax.get("test.html",null,{data:{b:111},complete:function(XMLHttpRequest, textStatus){
    console.log(XMLHttpRequest)
  }});


//关于原load方法中URL参数,里面空格后面为内容选择器,参考:http://www.w3school.com.cn/jquery/ajax_load.asp
//load源码分析:https://blog.csdn.net/liangklfang/article/details/49663845
  $("#results").load("test.html .navigate",function(){
    console.log("完成载入");
  })
});

   
Rss Comment  

没有相关评论

发表评论
请先注册,才能发表评论!
- 注册 -