AJAX请求封装函数

/**
    * ajax封装
    * url 发送请求的地址
    * data 发送到服务器的数据,数组存储,如:{"date": 2, "state": 1}
    * async 默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。
    * 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
    * type 请求方式("POST" 或 "GET"), 默认为 "GET"
    * dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text
    * successfn 成功回调函数
    * errorfn 失败回调函数
    */
   jQuery.ajaxFun = function(Obj) {
   //url, data, async, type, dataType, successfn, errorfn
   Obj.async = (Obj.async == null || Obj.async == "" || typeof(Obj.async) == "undefined") ? "true" : Obj.async;
   Obj.type = (Obj.type == null || Obj.type == "" || typeof(Obj.type) == "undefined") ? "post" : Obj.type;
   Obj.dataType = (Obj.dataType == null || Obj.dataType == "" || typeof(Obj.dataType) == "undefined") ? "json" : Obj.dataType;
   Obj.data = (Obj.data == null || Obj.data == "" || typeof(Obj.data) == "undefined") ? '' : Obj.data;
   Obj.contentType = (Obj.data == null || Obj.data == "" || typeof(Obj.data) == "undefined") ? 'application/json; charset=utf-8' : Obj.contentType;

      $.ajax({
         type: Obj.type,
         async: Obj.async,
         data: Obj.data,
         url: path,
         dataType: Obj.dataType,
         contentType:Obj.contentType,
         success: function(data) {
            if(!data.success) {//判断返回的data.success是否为false
            } else {
               if(Obj.success instanceof Function) {//判断调用时是否有回调函数(判断是否是函数)
                  Obj.success(data);
               }
            }
         },
         error: function(err) {
            if(Obj.error instanceof Function) {//判断调用时是否有回调函数(判断是否是函数)
               Obj.error(err);
            } else {
               errorfn(err);//调用全局错误函数
            }
         }
      });
   
};
   errorfn = function(err) {//全局错误函数
      console.log(err)
   }

猜你喜欢

转载自my.oschina.net/u/3686989/blog/1581129