无刷新分页实现-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

无刷新分页实现

简介: 有些情况为了更好的用户体验或者弹窗获取数据等,需要用到异步请求数据并且分页,这里用到了一个jquery的插件,可以方便快速的实现。 页码条样式 /*css scott style pagination*/ div.

有些情况为了更好的用户体验或者弹窗获取数据等,需要用到异步请求数据并且分页,这里用到了一个jquery的插件,可以方便快速的实现。

页码条样式

/*css scott style pagination*/

div.scott {
    padding-right: 3px; padding-left: 3px; padding-bottom: 3px; margin: 3px; padding-top: 3px; text-align: center; font-family:Verdana; font-size:12px;
}
div.scott a {
    border-right: #ddd 1px solid; padding-right: 5px; border-top: #ddd 1px solid; padding-left: 5px; padding-bottom: 2px; border-left: #ddd 1px solid; color: #88af3f; margin-right: 2px; padding-top: 2px; border-bottom: #ddd 1px solid; text-decoration: none
}
div.scott a:hover {
    border-right: #85bd1e 1px solid; border-top: #85bd1e 1px solid; border-left: #85bd1e 1px solid; color: #638425; border-bottom: #85bd1e 1px solid; background-color: #f1ffd6
}
div.scott a:active {
    border-right: #85bd1e 1px solid; border-top: #85bd1e 1px solid; border-left: #85bd1e 1px solid; color: #638425; border-bottom: #85bd1e 1px solid; background-color: #f1ffd6
}
div.scott span.current {
    border-right: #b2e05d 1px solid; padding-right: 5px; border-top: #b2e05d 1px solid; padding-left: 5px; font-weight: bold; padding-bottom: 2px; border-left: #b2e05d 1px solid; color: #fff; margin-right: 2px; padding-top: 2px; border-bottom: #b2e05d 1px solid; background-color: #b2e05d
}
div.scott span.disabled {
    border-right: #f3f3f3 1px solid; padding-right: 5px; border-top: #f3f3f3 1px solid; padding-left: 5px; padding-bottom: 2px; border-left: #f3f3f3 1px solid; color: #ccc; margin-right: 2px; padding-top: 2px; border-bottom: #f3f3f3 1px solid
}

页码条生成

<div id="content"></div>
 <div class="scott pagination"></div>

js代码

    <script src="~/Content/js/jquery-1.9.1.min.js"></script>
    <script src="~/js/jquery.pagination.js"></script>
    <script src="~/js/music_pagesort.js"></script>
   <script type="text/javascript">
    $(function () {
        music_load_data();
    })
    //加载数据
    function music_load_data() {
        var pageIndex = 0;
        var pageSize = 5;
        music_pagesort_ajax_pagesort(pageIndex, pageSize, "/home/test", function (_jsonlist, AllCount) {
            music_data_add(_jsonlist);
        });
    }
    //数据填充
    function music_data_add(data) {
        var _html = '<ol>';
        for (var i = 0; i < data.length; i++) {
            _html += '<li>'+data[i].videoTitle + "</li>";
        }
        _html += '</ol>';
        $("#content").html(_html);
    }
</script>

jquery.pagination.js代码

/**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
*/
jQuery.fn.pagination = function (maxentries, opts) {
    opts = jQuery.extend({
        items_per_page: 10,
        num_display_entries: 10,
        current_page: 0,
        num_edge_entries: 0,
        link_to: "#",
        prev_text: "Prev",
        next_text: "Next",
        ellipse_text: "...",
        prev_show_always: true,
        next_show_always: true,
        callback: function () { return false; }
    }, opts || {});
    return this.each(function () {
        /**
        * Calculate the maximum number of pages
        */
        function numPages() {
            return Math.ceil(maxentries / opts.items_per_page);
        }
        /**
        * Calculate start and end point of pagination links depending on 
        * current_page and num_display_entries.
        * @return {Array}
        */
        function getInterval() {
            var ne_half = Math.ceil(opts.num_display_entries / 2);
            var np = numPages();
            var upper_limit = np - opts.num_display_entries;
            var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
            var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(opts.num_display_entries, np);
            return [start, end];
        }
        /**
        * This is the event handling function for the pagination links. 
        * @param {int} page_id The new page number
        */
        function pageSelected(page_id, evt) {
            current_page = page_id;
            drawLinks();
            var continuePropagation = opts.callback(page_id, panel);
            if (!continuePropagation) {
                if (evt.stopPropagation) {
                    evt.stopPropagation();
                }
                else {
                    evt.cancelBubble = true;
                }
            }
            return continuePropagation;
        }
        /**
        * This function inserts the pagination links into the container element
        */
        function drawLinks() {
            panel.empty();
            var interval = getInterval();
            var np = numPages();
            // This helper function returns a handler function that calls pageSelected with the right page_id
            var getClickHandler = function (page_id) {
                return function (evt) { return pageSelected(page_id, evt); }
            }
            // Helper function for generating a single link (or a span tag if it'S the current page)
            var appendItem = function (page_id, appendopts) {
                page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1); // Normalize page id to sane value
                appendopts = jQuery.extend({ text: page_id + 1, classes: "current" }, appendopts || {});
                if (page_id == current_page) {
                    var lnk = $("<span class='current'>" + (appendopts.text) + "</span>");
                }
                else {
                    var lnk = $("<a>" + (appendopts.text) + "</a>")
                        .bind("click", getClickHandler(page_id))
                        .attr('href', opts.link_to.replace(/__id__/, page_id));
                }
                if (appendopts.classes) { lnk.removeAttr('class'); lnk.addClass(appendopts.classes); }
                panel.append(lnk);
            }
            // Generate "Previous"-Link
            if (opts.prev_text && (current_page > 0 || opts.prev_show_always)) {
                appendItem(current_page - 1, { text: opts.prev_text, classes: "disabled" });
            }
            // Generate starting points
            if (interval[0] > 0 && opts.num_edge_entries > 0) {
                var end = Math.min(opts.num_edge_entries, interval[0]);
                for (var i = 0; i < end; i++) {
                    appendItem(i);
                }
                if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
                    jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
                }
            }
            // Generate interval links
            for (var i = interval[0]; i < interval[1]; i++) {
                appendItem(i);
            }
            // Generate ending points
            if (interval[1] < np && opts.num_edge_entries > 0) {
                if (np - opts.num_edge_entries > interval[1] && opts.ellipse_text) {
                    jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
                }
                var begin = Math.max(np - opts.num_edge_entries, interval[1]);
                for (var i = begin; i < np; i++) {
                    appendItem(i);
                }
            }
            // Generate "Next"-Link
            if (opts.next_text && (current_page < np - 1 || opts.next_show_always)) {
                appendItem(current_page + 1, { text: opts.next_text, classes: "disabled" });
            }
        }
        // Extract current_page from options
        var current_page = opts.current_page;
        // Create a sane value for maxentries and items_per_page
        maxentries = (!maxentries || maxentries < 0) ? 1 : maxentries;
        opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0) ? 1 : opts.items_per_page;
        // Store DOM element for easy access from all inner functions
        var panel = jQuery(this);
        // Attach control functions to the DOM element 
        this.selectPage = function (page_id) { pageSelected(page_id); }
        this.prevPage = function () {
            if (current_page > 0) {
                pageSelected(current_page - 1);
                return true;
            }
            else {
                return false;
            }
        }
        this.nextPage = function () {
            if (current_page < numPages() - 1) {
                pageSelected(current_page + 1);
                return true;
            }
            else {
                return false;
            }
        }
        // When all initialisation is done, draw the links
        drawLinks();
    });
}

music_pagesort.js代码

/*
分页js调用说明
传入参数
    pageIndex:当前页
    pageSize:每页展示多少数据
    serverUrl:请求服务端地址
*/
//showcase_pagesort
//分页      
function music_pagesort_ajax_pagesort(pageIndex, pageSize, serverUrl, _CallBackFunction) {
    $.ajax({
        type: "POST",
        dataType: "text",
        url: serverUrl,      //提交到一般处理程序请求数据   
        data: "pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize,
    //提交两个参数:pageIndex(页面索引),pageSize(显示条数)                   
        success: function (serverData) {
            var jsondata = $.parseJSON(serverData);
        if (jsondata.status == 0) {
            if ($.isFunction(_CallBackFunction)) {
                _CallBackFunction(jsondata.data.list, jsondata.data.count);
            }
            //分页,PageCount是总条目数,这是必选参数,其它参数都是可选
            $(".pagination").pagination(jsondata.data.count, {
                callback: PageCallback,  //PageCallback() 为翻页调用次函数。
                prev_text: "«",
                next_text: "»",
                items_per_page: pageSize,
                num_edge_entries: 2,       //两侧首尾分页条目数
                num_display_entries: 6,    //连续分页主体部分分页条目数
                current_page: pageIndex,   //当前页索引                      
            });
            //翻页调用   
            function PageCallback(index, jq) {
                music_pagesort_ajax_pagesort(index, pageSize, serverUrl, _CallBackFunction);
            }
        } else {
            alert(jsondata.msg);
        }
        //alert();
        //将返回的数据追加到表格   
    }
});
}

服务端代码(.net mvc为例)

 public ActionResult Test()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Test(FormCollection collection)
        {
            int pageindex = Convert.ToInt32(Request["pageIndex"]);
            int pagesize = Convert.ToInt32(Request["pageSize"]);
            string text = Request["text"];

            var list = db.zhancaiw_video.Where(c=>true).OrderByDescending(c=>c.videoID).Skip((pageindex-1)*pagesize).Take(pagesize);

            var count = db.zhancaiw_video.Where(c => true).Count();

            return Content(JsonReturn(Enum_ReturnStatus.成功, "数据获取成功", new { list = list, count = count }));
        }

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章
最新文章
相关文章