jquery之ajax请求工具类
更新:HHH   时间:2023-1-7


js中调用方式:

var params = {};
params["aakey"]="aavalue";
params["bbkey"]="bbvalue";
$.cosajax({
    url: path + "**.action",
    data: params, //一个对象,包含很多键值对,jquery自动转化为aakey=aavalue&bbkey=bbvalue的形式
    callback: function(result) {
}
});


function checkSessionTimeOut(result) { //增加session超时判断
    if (result &&!(result.success) && result.message == 'timeout') {
        top.document.location= path + '/frame.action';
        returntrue;
    }
    return false;
}
function showTip(msg,callback)
    {
        $("#mask_bg").css("z-index","9999"); //窗口置于最上面
        $("#okbtn").unbind();  //删除okbtn的其他事件
        $("#mask_new").show();
        $("#okbtn").one('click', callback); //增加点击事件,隐藏tip
    }   
function hideTip()
    {
        $("#mask_new").hide();
        $("#mask_bg").hide();
    }
jQuery.extend({
   cosajax : function(opts) {
        opts= jQuery.extend({
            url : "",
            data : "",
            isWait: false,
            isClose: true,
            callback : function() {
                returnfalse;
            },
            fail : function() {
                returnfalse;
            }
        },opts || {});  //逗号后面opts||{}是对前面的扩展
    
        $.ajax({
            type : "POST",
            dataType : "json",
            url : opts.url,
            async : false,
            data : opts.data, //多个参数用&连接
            timeout: 180000,  
            beforeSend : function() {
            },
            complete : function(result) {
             if (!opts.isWait) {  //成功失败都会调用complete方法
                 hiddenWait();
             }
            },
            success : function(result) {
             // 增加session超时判断
                if(checkSessionTimeOut(result)) {
                    return;
                }
                
                if (result.success) {
                    opts.callback(result);  //调用opts中callback方法
                }else{
                    if(opts.isClose) {  //关闭窗口
                        closeWindows();
                        var errTipMessage =result.message;
                        switch (result.message) {
                            case'500':
                                errTipMessage=”操作失败”;
                                break;
                            default:
                                errTipMessage= result.message;
                                break;
                        }
                        showTip(errTipMessage,hideTip); //hiteTip是点击事件的回调函数
                    } else {
                        hiddenWait();
                        opts.fail(result);
                    }
                }
            },
            error : function() {
                if(opts.isClose) {
                    closeWindows();
                    showTip(“操作失败”,hideTip);
                }else{
                    hiddenWait();
                    opts.fail();
                }
            }
        });
   }
});





返回web开发教程...