常用js扩展方法

<code lang="javascript" line="1">
//自动和当前域名一致
apiHost = "http://" + getHost(location.href) + "/";
try {
    if (typeof (appPath) == 'undefined') {
        appPath = "/";
    }
} catch (e) {
}

/*************JS扩展方法*****************/
String.prototype.TrimEnd = function (v)//去除字符串结尾指定字符
{
    if (this.substring(this.length - 1, this.length) == v) {
        return this.substring(0, this.length - 1);
    }
    else {
        return this;
    }
}
String.prototype.Trim = function ()   //去除字符串前后空格
{
    return this.replace(/(^[\s]*)|([\s]*$)/g, "");
}
String.prototype.LenCH = function () {
    return this.replace(/[^\x00-\xff]/g, "xx").length;
}

String.prototype.IsNaN = function () {//是否是数字
    var filter = /^\d+$/;
    return filter.test(this);
}
String.prototype.IsPhone = function () {
    var filter = /^1[3|4|5|8][0-9]\d{4,8}$/;
    return filter.test(this);
}
String.prototype.IsEmail = function () {
    var filter = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
    return filter.test(this);
}
String.prototype.IsNullOrEmpty = function () {
    if (typeof (this) == "undefined") {
        return true;
    }
    else if (this.length == 0) {
        return true;
    }
    return false;
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

String.prototype.IsTelephone = function () {
    var filter = /^0[0-9]{2,3}-[2-9][0-9]{7}(-[0-9]{1,4})?$/
    return filter.test(this);
}
String.prototype.IsQQ = function () {
    var filter = /^[1-9][0-9]{4,12}$/;
    return filter.test(this);
}


/*****************共用方法*******************/
function getHost(url) {
    var host = "null";
    if (typeof url == "undefined" || null == url) {
        return host;
    }
    var regex = /.*\:\/\/([^\/]*).*/;
    if (url.indexOf("://") == -1) {
        url = "http://" + url;
    }
    var match = url.match(regex);
    if (typeof match != "undefined" && null != match) {
        host = match[1];
    }
    return host;
}
function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}
/*******************JQuery扩展************************/

var apiAjax = {
    parseParam: function (param) {
        var res = { url: '', data: '' };
        //创建url
        if (param.action.indexOf("Login") != -1 || param.action.indexOf("Support") != -1) {
            param.action = "inner." + param.action;
        }
        if (param.action.indexOf("Guest") != -1) {
            param.action = "out." + param.action;
        }

        res.url = apiHost + "/" + param.action.split('.').join('/');

        //创建表单数据
        var paramsArr = new Array();

        if (typeof (param.data) == "object") {
            for (var p in param.data) {

                var pvalue = param.data[p];

                if (jQuery.isFunction(pvalue)) {
                    continue;
                }

                if (typeof (pvalue) != "object") {
                    //var val = typeof (pvalue) == "string" ? pvalue.replace(/\+/g, "%2B").replace(/\&/g, "%26").replace(/\</g, " ").Trim().replace(/\>/g, " ").Trim() : pvalue;
                    var val = typeof (pvalue) == "string" ? encodeURIComponent(pvalue.Trim()) : pvalue;
                    paramsArr.push(p + "=" + val);
                }
                else {
                    for (var arrValue in pvalue) {
                        var v = pvalue[arrValue];
                        if (jQuery.isFunction(v)) {
                            continue;
                        }
                        //var val = typeof (pvalue) == "string" ? v.replace(/\+/g, "%2B").replace(/\&/g, "%26").trim().replace(/\</g, " ").trim().replace(/\>/g, " ").trim() : v;
                        var val = typeof (pvalue) == "string" ? encodeURIComponent(v.Trim()) : v;

                        paramsArr.push(p + "=" + val);
                    }
                }
            }
        }

        var token = $.cookie('MarketingLiveChatUserToken') + "";

        //设置token
        paramsArr.push("____token=" + token);
        ////设置时间戳
        res.data = paramsArr.join('&');

        if (typeof (param.data) != "object") {
            res.data += '&' + param.data;
        }
        return res;
    },
    sendAjax: function (param, type, dataType, _success) {

        param = this.parseParam(param);
        if (type == null) {
            type = "POST";
        }

        var ajaxParam = {
            type: type,
            url: param.url,
            data: param.data,
            timeout: 120 * 1000
        };

        if (dataType == null) {
            ajaxParam.dataType = "json";
        }
        else {
            ajaxParam.dataType = "text";
        }


        ajaxParam.success = function (res) {

            if (ajaxParam.dataType == "json") {
                if (!res.Success) {
                    if (res.Code == 1) {
                        //alert("系统错误");
                        return;
                    }
                    if (res.Code == 2) {
                        alert(res.Msg);
                        window.parent.window.parent.window.parent.location.href = appPath;
                        return;
                    }
                }
            }

            if (_success) {
                _success(res);
            }

        }
        ajaxParam.error = function (jqXHR, textStatus, errorThrown) {
            if (textStatus == "parsererror") {
                alert("数据结果转换错误");
            }
            if (textStatus == "timeout") {
                alert("请求超时");
            }
            if (textStatus == "abort") {
                alert("请求中断");
            }
            if (textStatus == "error") {
                // alert("服务器端错误");
            }
        }
        jQuery.ajax(ajaxParam);
    },
    get: function (param, success, dataType) {
        this.sendAjax(param, "get", dataType, success);
    },
    post: function (param, success, dataType) {
        this.sendAjax(param, "post", dataType, success);
    }
};
//表单数据转换
(function ($) {
    $.fn.toObject = function (p) {
        for (var i = 0; i < this.length; i++) {
            var arr = $(this[i]).serializeArray();
            var temp = new Array();
            for (var j = 0; j < arr.length; j++) {
                var name = arr[j].name;
                var item = temp[name];
                if (typeof (item) == 'undefined') {
                    temp[name] = new Array();
                    item = temp[name];
                }
                item.push(arr[j].value);
            }

            var obj = {};
            for (var name in temp) {
                if (temp[name].length == 1) {
                    var info = temp[name][0];
                    info = info.replace(/(\r\n)/g, "★");
                    info = info.replace(/\'/g, "\\'");
                    var fun = "obj." + name + "='" + info + "';";
                    eval(fun);
                }
                else {
                    var _arr = new Array();
                    for (var k = 0; k < temp[name].length; k++) {
                        _arr.push("'" + temp[name][k] + "'");
                    }
                    var arrStr = "[" + _arr.join(',') + "]";
                    var fun = "obj." + name + "=" + arrStr + ";";
                    eval(fun);
                }
            }
            return obj;
        }
    };
    $.fn.bindForm = function (data) {
        $(this).each(function (index, form) {
            form = $(form);
            for (var p in data) {
                var input = $("#" + p, form);
                var val = data[p];
                input.val(val);
            }
        });
    };
    $.fn.bindSelect = function (data, fieldName, valueName, sval) {
        $(this).each(function (index, sel) {
            sel = $(sel).html('');
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                sel.append('<option value="' + obj[valueName] + '">' + obj[fieldName] + '</option>');
            }
            if (sval && sval != '') {
                sel.val(sval);
            }
        });
    };
})(jQuery);
/******页面加载方法**********/
var permission = {
    data: [],
    check: function (id) {
        if (permission.data) {
            for (var i = 0; i < permission.data.length; i++) {
                if (permission.data[i] == id) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    },
    showIfHas: function (s) {
        jQuery(s).each(function () {
            var ex = jQuery(this);
            var id = ex.attr("id");
            if (id) {
                if (permission.check(id)) {
                    ex.show();
                }
            }
        });
    },
    autoShowIfHas: function () {
        $FlashCookie.ready(function () {
            permission.data = new Array();
            $.each($FlashCookie.get("__Button"), function () {
                permission.data.push(this.PowerNameEN);
            });

            if (permission.data) {
                jQuery(".permission").each(function () {
                    var ex = jQuery(this);
                    ex.hide();
                    permission.showIfHas(ex);

                });
            }
        });
    }

};

//加载产品ID
//window.ProductId = $.cookie('__BaseInfo') == null ? 4 : $.evalJSON($.cookie('__BaseInfo')).ProductId;
//window.IsFirst = false;

//$(document).ready(function () {
//    permission.autoShowIfHas();
//});
</code>
分享到: