本人微信公众号"aeolian"~

ajax

ajax封装

        /*ajax封装*/
        jQuery.ax = function(url, data, type, successfn, errorfn, async) {
            success_fn = successfn;  //防止ax执行完回收successfn,所以赋给全局success_fn
            error_fn = errorfn;
            var contentType = "application/x-www-form-urlencoded; charset=utf-8";  //或者"application/json; charset=utf-8";根据后台架构来
            var contype_application = "application/x-www-form-urlencoded";
            if ((data == null || data == "" || typeof(data) == "undefined")) {
                $.ajax({
                    type: type,
                    async: async,
                    url: url,
                    dataType: "json",
                    beforeSend: function(request) {
                        request.setRequestHeader("Content-type", contype_application);
                    },
                    contentType: contentType,
                    success: function(d) {
                        successfun(d)
                    },
                    error: function(e) {
                        errorfn(e);
                    }
                });
            } else {
                $.ajax({
                    type: type,
                    async: async,
                    url: url,
                    data: data,   //根据后台处理机制,也可以写成JSON.stringify(data)
                    dataType: "json",
                    contentType: contentType,
                    beforeSend: function(request) {
                        request.setRequestHeader("Content-type", contype_application);
                    },
                    success: function(d) {
                        success_fn(d)
                    },
                    error: function(e) {
                        error_fn(e);
                    }
                });
            }
        }

参数

url : ajax请求的url
data : 请求参数
type: GET或者POST
successfn : 成功函数
errorfn : 失败函数
async : 是否异步,异步true,同步false

调用

      var data = {id:module.id,modulename:'未命名'};
      $.ax('./permission/insertSelective', data, 'POST', function(d) {
          /*success*/
      }, function(e) {
          /*error*/
      }, false); //同步
点赞

Leave a Reply

Your email address will not be published. Required fields are marked *