当前位置 : 主页 > 网络编程 > JavaScript >

jquery-extensions.js,针对序列化和反序列

来源:互联网 收集:自由互联 发布时间:2021-06-28
序列化成json格式,方便post、get等请求,反序列:将接受的obj赋值给对应的对象 /* 序列化 var postdata = $('input,select,textarea').serializeJson() 反序列 $('input,select,textarea').deserialize(data) 分页:针
序列化成json格式,方便post、get等请求,反序列:将接受的obj赋值给对应的对象
/*
    序列化 var postdata = $('input,select,textarea').serializeJson() 
    反序列 $('input,select,textarea').deserialize(data)
    分页:针对jquery.myPagination.js进行了二次封装,
    $('.pagination').loadPageList(pagesize, total, function (index) {点击分页的回调函数,Index为点击页码})
    by:lb
    date:2017-07-21 11:45:02
*/
(function ($) {
    //序列化
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
    //反序列
    $.fn.deserialize = function (data) {
        var _self = this;
        if (_self == null || _self.length == 0) {
            return;
        }
        _self.each(function (index, item) {
            for (var key in data) {
                if (item.name == key) {
                    if (item.type == 'radio') {
                        if ($(item).val() == data[key]) {
                            $(item).prop('checked', true);
                        } else {
                            $(item).removeProp('checked');
                        }
                    } else {
                        $(item).val(data[key]);
                    }
                }
            }
        });
    };
    $.fn.loadPageList = function (pagesize, total, callback) {
        var item = this;
        item.html('');
        var pagecount = 0;
        if (total % pagesize == 0)
            pagecount = parseInt(total / pagesize);
        else
            pagecount = parseInt(total / pagesize) + 1;
        if (pagecount < 2) {
            item.html('');
            return;
        }
        var showPageNum = 10;
        if (pagecount < 10)
            showPageNum = pagecount;
        item.myPagination({
            currPage: 1,
            pageCount: pagecount,
            pageSize: showPageNum,
            cssStyle: 'pagination',
            info: {
                first: '首页',
                last: '尾页',
                prev: '上一页',
                next: '下一页'
            },
            callbacks: function (currPage) {
                callback(currPage);
            }
        });
    },
    $.fn.button = function (type) {
        switch (type) {
            case 'loading':
                $(this).css('cursor', 'not-allowed');
                $(this).css('opacity', '0.5');
                $(this).attr('disabled', true);
                $(this).text($(this).attr('data-loading'));
                break;
            case 'reset':
                $(this).css('cursor', 'pointer');
                $(this).css('opacity', '1');
                $(this).removeAttr('disabled');
                $(this).text($(this).attr('data-reset'));
                break;
            default:
        }
    },
//按钮倒计时,配合bootstrap
    $.fn.CountDown = function(num) {
        var _self = $(this);
        _self.button('loading').val(num + ' s');
        for (var i = 0; i < num-1; i++) {
            setTimeout(function () {
                num--;
                if (num ==1) {
                    _self.button('reset');
                } else {
                    _self.val((num) + " s");
                }
            }, 1000 * i);
        }
    };
    //使用bootstrap的样式 分页
    $.fn.extendPagination = function (options) {
        var defaults = {
            //pageId:'',
            totalCount: '',
            showPage: '10',
            limit: '5',
            callback: function () {
                return false;
            }
        };
        $.extend(defaults, options || {});
        if (defaults.totalCount == '') {
            $(this).empty();
            return false;
        } else if (Number(defaults.totalCount) <= 0) {
            $(this).empty();
            return false;
        }
        if (defaults.showPage == '') {
            defaults.showPage = '10';
        } else if (Number(defaults.showPage) <= 0) defaults.showPage = '10';
        if (defaults.limit == '') {
            defaults.limit = '5';
        } else if (Number(defaults.limit) <= 0) defaults.limit = '5';
        var totalCount = Number(defaults.totalCount), showPage = Number(defaults.showPage),
            limit = Number(defaults.limit), totalPage = Math.ceil(totalCount / limit);
        if (totalPage > 0) {
            var html = [];
            html.push(' 
 
    '); html.push(' '); html.push(' '); if (totalPage <= showPage) { for (var i = 1; i <= totalPage; i++) { if (i == 1) html.push('
  • ' + i + '
  • '); else html.push('
  • ' + i + '
  • '); } } else { for (var j = 1; j <= showPage; j++) { if (j == 1) html.push('
  • ' + j + '
  • '); else html.push('
  • ' + j + '
  • '); } } html.push(' '); html.push('
'); $(this).html(html.join('')); if (totalPage > showPage) $(this).find('ul.pagination li.next').prev().removeClass('hidden'); var pageObj = $(this).find('ul.pagination'), preObj = pageObj.find('li.previous'), currentObj = pageObj.find('li').not('.previous,.disabled,.next'), nextObj = pageObj.find('li.next'); function loopPageElement(minPage, maxPage) { var tempObj = preObj.next(); for (var i = minPage; i <= maxPage; i++) { if (minPage == 1 && (preObj.next().attr('class').indexOf('hidden')) < 0) preObj.next().addClass('hidden'); else if (minPage > 1 && (preObj.next().attr('class').indexOf('hidden')) > 0) preObj.next().removeClass('hidden'); if (maxPage == totalPage && (nextObj.prev().attr('class').indexOf('hidden')) < 0) nextObj.prev().addClass('hidden'); else if (maxPage < totalPage && (nextObj.prev().attr('class').indexOf('hidden')) > 0) nextObj.prev().removeClass('hidden'); var obj = tempObj.next().find('a'); if (!isNaN(obj.html())) obj.html(i); tempObj = tempObj.next(); } } function callBack(curr) { defaults.callback(curr, defaults.limit, totalCount); } currentObj.click(function (event) { event.preventDefault(); var currPage = Number($(this).find('a').html()), activeObj = pageObj.find('li[class="active"]'), activePage = Number(activeObj.find('a').html()); if (currPage == activePage) return false; if (totalPage > showPage && currPage > 1) { var maxPage = currPage, minPage = 1; if (($(this).prev().attr('class')) && ($(this).prev().attr('class').indexOf('disabled')) >= 0) { minPage = currPage - 1; maxPage = minPage + showPage - 1; loopPageElement(minPage, maxPage); } else if (($(this).next().attr('class')) && ($(this).next().attr('class').indexOf('disabled')) >= 0) { if (totalPage - currPage >= 1) maxPage = currPage + 1; else maxPage = totalPage; if (maxPage - showPage > 0) minPage = (maxPage - showPage) + 1; loopPageElement(minPage, maxPage) } } activeObj.removeClass('active'); $.each(currentObj, function (index, thiz) { if ($(thiz).find('a').html() == currPage) { $(thiz).addClass('active'); callBack(currPage); } }); }); preObj.click(function (event) { event.preventDefault(); var activeObj = pageObj.find('li[class="active"]'), activePage = Number(activeObj.find('a').html()); if (activePage <= 1) return false; if (totalPage > showPage) { var maxPage = activePage, minPage = 1; if ((activeObj.prev().prev().attr('class')) && (activeObj.prev().prev().attr('class').indexOf('disabled')) >= 0) { minPage = activePage - 1; if (minPage > 1) minPage = minPage - 1; maxPage = minPage + showPage - 1; loopPageElement(minPage, maxPage); } } $.each(currentObj, function (index, thiz) { if ($(thiz).find('a').html() == (activePage - 1)) { activeObj.removeClass('active'); $(thiz).addClass('active'); callBack(activePage - 1); } }); }); nextObj.click(function (event) { event.preventDefault(); var activeObj = pageObj.find('li[class="active"]'), activePage = Number(activeObj.find('a').html()); if (activePage >= totalPage) return false; if (totalPage > showPage) { var maxPage = activePage, minPage = 1; if ((activeObj.next().next().attr('class')) && (activeObj.next().next().attr('class').indexOf('disabled')) >= 0) { maxPage = activePage + 2; if (maxPage > totalPage) maxPage = totalPage; minPage = maxPage - showPage + 1; loopPageElement(minPage, maxPage); } } $.each(currentObj, function (index, thiz) { if ($(thiz).find('a').html() == (activePage + 1)) { activeObj.removeClass('active'); $(thiz).addClass('active'); callBack(activePage + 1); } }); }); } }; })(jQuery);
Layer提示框+Ajax封装
$.extend({
    POST: function (url, data, success, async) {
        data = $.extend(data, { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() });
        $.ajax({
            url: url,
            type: "post",
            data: data,
            async: async,
            dataType: 'json',
            success: function (data) {
                success(data);
            },
            error: function (ms, s, e) {
                var res = {};
                res.flag = false;
                res.msg = s;
                res.total = 0;
                success(res);
            }
        });
    },
    GET: function (url, data, success, async) {
        data = $.extend(data, { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() });
        if (async == undefined) {
            async = true;
        }
        $.ajax({
            url: url,
            type: "GET",
            data: data,
            dataType: 'json',
            async: async,
            success: function (data) {
                success(data);
            },
            error: function (ms, s, e) {
                var res = {};
                res.flag = false;
                res.msg = s;
                res.data = '';
                success(res);
            }
        });
    },
    Delete: function (url, data, success) {
        parent.layer.confirm("确认要删除该数据?", {
            btn: ['确定', '取消'] //按钮
        }, function () {
            $.POST(url, data, function (data) {
                if (data.flag) {
                    $.Success("删除成功");
                    success(data);
                } else {
                    $.Error(data.msg);
                }
            }, false);
        }, function () {

        });
    },
    Form: function (url, data, success) {
        $.POST(url, data, function (data) {
            if (data.flag) {
                success(data);
            } else {
                $.Error(data.msg);
            }
        }, false);
    },
    Confirm:function(title,callback) {
        parent.layer.confirm(title, {
            btn: ['确定', '取消'] //按钮
        }, function() { callback(); }, function() {});
    },
    Alert: function (msg, config) {
        var _config = {
            time: 2500,
            anim: 0
        }
        _config = $.extend(_config, config);
        top.layer.msg(msg, _config);
    },
    Warm: function (msg) {
        msg = '

' + msg + '

'; $.Alert(msg, { anim: 6 }); }, Error: function (msg) { msg = '

' + msg + '

'; $.Alert(msg, { anim: 6 }); }, Success: function (msg) { msg = '

' + msg + '

'; $.Alert(msg, { anim: 0 }); }, OpenWindow: function (url) { setTimeout(function () { window.location.href = url; }, 200); }, modalOpen: function (options) { var defaults = { id: null, title: '系统窗口', width: "100px", height: "100px", url: '', shade: 0.3, btn: ['确认', '关闭'], btnclass: ['btn btn-success', 'btn btn-danger'], callBack: null }; var options = $.extend(defaults, options); var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px'; var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px'; top.layer.open({ id: options.id, type: 2, shade: options.shade, title: options.title, fix: false, area: [_width, _height], content: options.url, btn: options.btn, btnclass: options.btnclass, yes: function () { var frm = top.$('#' + options.id).find('iframe')[0].contentWindow; options.callBack(frm); }, cancel: function () { return true; } }); }, currentWindow: function () { var iframeId = top.$("#txtContentBody").attr("id"); return top.frames[iframeId].contentWindow; }, modalClose: function () { var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引 var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose"); var IsClose = $IsdialogClose.is(":checked"); if ($IsdialogClose.length == 0) { IsClose = true; } if (IsClose) { top.layer.close(index); } else { location.reload(); } } });
未标题-1.png
网友评论