公共Ajax封装

公共Ajax封装

//*ajax公共方法,后面的参数存在选传时,左边的参数就是必传,否则无法正确匹配
//* 参数一(必传):url 发送请求的地址
//* 参数二(选传,默认为空):data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1}
//* 参数三(选传,默认为true):showMsg 出错时是否弹出提示框
//* 参数四(选传,默认为false):async 同步或异步请求。为true时,所有请求均为异步请求。为false时,所有请求为同步请求。
//*                              注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
//* 参数五(选传,默认值为"POST")type 请求方式("POST" 或 "GET")
//* 参数六(选传,默认值为"json")dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text
//* 返回值:Object对象,默认三个属性,即code(成功时为0)、data(成功时为数据对象)、errmsg(错误时的网页错误对象)
function GafeAjax(url) {
    var result = new Object();
    result.code = "1";

    var data = {};
    if (arguments.length > 1) {
        if (typeof (arguments[1]) == "string") {
            data = JSON.parse(arguments[1]);
        }
        else {
            data = arguments[1];
        }
    }

    var showMsg = true;
    if (arguments.length > 2) {
        showMsg = arguments[2];
    }
    var async = false;
    if (arguments.length > 3) {
        async = arguments[3];
    }
    var type = "post";
    if (arguments.length > 4) {
        type = arguments[4];
    }
    var dataType = "json";
    if (arguments.length > 5) {
        dataType = arguments[5];
    }
    async = (async == null || async == "" || typeof (async) == "undefined") ? false : async;
    type = (type == null || type == "" || typeof (type) == "undefined") ? "post" : type;
    dataType = (dataType == null || dataType == "" || typeof (dataType) == "undefined") ? "json" : dataType;
    $.ajax({
        type: type,
        async: async,
        data: data,
        url: url,
        dataType: dataType,
        success: function (res) {
            result.code = "0";//表示成功
            result.data = res;
        },
        error: function (err) {
            if (showMsg) {
                alert(err.responseText);
            }
            result.errmsg = err;
        }
    });
    return result;
}

调用

var ref = GafeAjax("/xx/xxxxxx", { where: where, Index: pageindex == 0 ? pageindex : pageindex - 1, PageCount: pagecount },false);
            if (ref.code == "0") {
                dataa = ref.data;
            }
            else {
                layer.msg(ref.errmsg.responseText);
            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值