简体   繁体   English

Bootstrap数据表分页仅显示按钮,但在Grails中不起作用

[英]Bootstrap datatable pagination only showing buttons but not working in Grails

I am using Grails 2.4.2. 我正在使用Grails 2.4.2。 and bootstrap datatable for Grails. 并引导Grails的数据表。 All works fine for datatable in my index page except for pagination. 除分页外,所有这些都对我的索引页中的数据表正常工作。 It shows all the related buttons for pagination but don't paginate. 它显示了所有相关的分页按钮,但不分页。 Also there is another div where paginate also shown and work but not with datatable ? 另外还有另一个div,其中分页符也可以显示和工作,但不能与datatable一起使用吗? Here are my attempts below :: 这是我在下面的尝试::

my controller index :: 我的控制器索引::

def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    respond Audio.list(params), model: [audioInstanceCount: Audio.count()]
}

my index view [sorry for uploading the full view,but to express] :: 我的索引视图[抱歉上传完整视图,但表示出来] ::

 <html>
    <head>
        <meta name="layout" content="stream">
        <g:set var="entityName" value="${message(code: 'audio.label', default: 'Audio')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>
        <script>
            $(document).ready(function() {
                $('#example').dataTable({
                    "sPaginationType": "full_numbers"
                });
            } );
        </script>
    </head>
    <body>
    <div class="buttons pull-right" style="margin-top: 5px;padding-right: 5px;">
        <a class="btn btn-primary" href="${createLink(controller: 'dashboard', action: 'homePageStream')}"><g:message code="default.home.label"/></a>
        <g:link class="btn btn-info" action="create"><g:message code="default.create.label" args="[entityName]" /></g:link>
    </div>

    <div id="list-audio" class="content scaffold-list" role="main">
        <div class="panel panel-info">
            <div class="panel-heading">
                <h5><g:message code="default.list.label" args="[entityName]"/></h5>
            </div>

            <div class="panel panel-body">
                <g:if test="${flash.message}">
                    <div class="message" role="status">${flash.message}</div>
                </g:if>
                <div class="col-md-12">
                <table id="example" class="table table-bordered table-hover" cellspacing="0" width="100%">
                    <thead>
                    <tr>
                        <th>Title</th>
                        <th>Short Description</th>
                        <th>Stream Type</th>
                        <th style="text-align: center;">Total Download</th>
                        <th style="text-align: center;">Active</th>
                        <th style="text-align: center;">Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <g:each in="${audioInstanceList}" status="i" var="audioInstance">
                        <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">

                            <td>${fieldValue(bean: audioInstance, field: "title")}</td>

                            <td>${fieldValue(bean: audioInstance, field: "shortDesc")}</td>

                            <td>${fieldValue(bean: audioInstance, field: "streamType")}</td>

                            <td align="right">${fieldValue(bean: audioInstance, field: "downloadCount")}</td>

                            %{--<td><g:formatBoolean boolean="${audioInstance.isActive}"/></td>--}%
                            <g:if test="${audioInstance.isActive}">
                                <td align="center"><span class="glyphicon glyphicon-ok" title="Active"></span></td>
                            </g:if>
                            <g:else>
                                <td align="center"><span class="glyphicon glyphicon-remove-sign" title="In-Active"></span></td>
                            </g:else>

                            <td align="center">
                                <g:link class="actionLink" action="changeActiveStatus" id="${audioInstance.id}"><span class="glyphicon glyphicon-retweet" title="Change Status"></span></g:link>
                                <g:link class="actionLink" action="edit" id="${audioInstance.id}"><span class="glyphicon glyphicon-edit" title="Edit"></span></g:link>
                                <g:link class="actionLink" action="deleteRow" id="${audioInstance.id}"><span class="glyphicon glyphicon-remove" title="Delete"></span></g:link>
                            </td>

                        </tr>
                    </g:each>
                    </tbody>
                </table>
                    <div class="pagination">
                        <g:paginate total="${audioInstanceCount ?: 0}"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </body>
</html>

here is my pagination image where only shows button but don't work :: 这是我的分页图像,其中仅显示按钮但不起作用::

分页问题

EDIT 编辑

here are my javascript >> 这是我的JavaScript >>

$('#example').dataTable({
    "sPaginationType": "full_numbers",
    "processing": true,
    "serverSide": true,
    "ajax": "${createLink(controller:'audio', action:'ajaxAudioList')}"
});

here are my controller action >> 这是我的控制器动作>>

def ajaxAudioList(){
    def audioInstanceList = Audio.getAll()
    render audioInstanceList as JSON
}

here are my table >> 这是我的桌子>>

<table id="example" class="table table-bordered table-hover" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Title</th>
            <th>Short Description</th>
            <th>Stream Type</th>
            <th style="text-align: center;">Total Download</th>
            <th style="text-align: center;">Active</th>
            <th style="text-align: center;">Action</th>
        </tr>
    </thead>                    
</table>

I have created an demo of server side datatable for which I have used datatable v1.10.7 , following is my controller 我创建了一个服务器端数据表演示,使用了v1.10.7 ,下面是我的控制器

//This action just render the index view
def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    render view: 'index'
}

/**
* This action is actually populating the user data in the data table.
* NOTE - datatable need JSON response and list in data key
* I have used projection to get the list of list that is required for
* datatable
**/
def getUsers() {
    String search = params["search[value]"]
    List userList = User.createCriteria().list([max: params.length ?: 10, offset: params.start ?: 0]) {
        if (search) {
            or {
                ilike('firstName', "%${search}%")
                ilike('lastName', "%${search}%")
                ilike('contactNumber', "%${search}%")
            }
        }

        projections {
            property('firstName')
            property('lastName')
            property('age')
            property('contactNumber')
        }
    }

    Map result = [draw: params.draw, recordsTotal: userList.totalCount, recordsFiltered: userList.totalCount, data: userList]
    render result as JSON
}

and view - 并查看-

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
        <th>Contact Number</th>
    </tr>
    </thead>
    <tfoot>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
        <th>Contact Number</th>
    </tr>
    </tfoot>
</table>

<script type="text/javascript">
    var goForSearch;
    $(function () {
        $('#example').dataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "${g.createLink(controller: 'user', action: 'getUsers')}"
        });
    });
</script>

Hope this helps. 希望这可以帮助。

NOTE - I have written the code for pagination and search. 注意-我已经编写了用于分页和搜索的代码。 For sorting you need to add some more code. 为了进行排序,您需要添加更多代码。 Use params['order[0][column]'] and params["order[0][dir]"] for sorting. 使用params['order[0][column]']params["order[0][dir]"]进行排序。

You can try the following code. 您可以尝试以下代码。

View page.. 查看页面

<table id="example" class="table table-bordered table-hover" cellspacing="0" width="100%">
                <thead>
                <tr>
                    <th>Title</th>
                    <th>Short Description</th>
                    <th>Stream Type</th>
                    <th style="text-align: center;">Total Download</th>
                    <th style="text-align: center;">Active</th>
                    <th style="text-align: center;">Action</th>
                </tr>
                </thead>
                <tbody>
                <g:each in="${dataReturn}" var="dataSet" status="i">
                    <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">

                        <td>${dataSet[0]}</td>
                            <td>${dataSet[1]}</td>
                            <td>${dataSet[2]}</td>
                            <td align="right">${dataSet[3]}</td>
                            <td>${dataSet[4]}</td>

                        <td align="center">
                            <g:link class="actionLink" action="changeActiveStatus" id="${dataSet.DT_RowId}"><span class="glyphicon glyphicon-retweet" title="Change Status"></span></g:link>
                            <g:link class="actionLink" action="edit" id="${dataSet.DT_RowId}"><span class="glyphicon glyphicon-edit" title="Edit"></span></g:link>
                            <g:link class="actionLink" action="deleteRow" id="${dataSet.DT_RowId}"><span class="glyphicon glyphicon-remove" title="Delete"></span></g:link>
                        </td>

                    </tr>
                </g:each>
                </tbody>
            </table>

Remove pagination div. 删除分页div。 Pagination will add by dataTable. 分页将通过dataTable添加。 Use the following javascript. 使用以下javascript。

<script>
jQuery(function ($) {
        $('#example').dataTable({
                    "bAutoWidth": true,
                    "bServerSide": true,
                    "iDisplayLength": 10,
                    "deferLoading": ${totalCount?:0},
                    "sAjaxSource": "${g.createLink(controller: 'audio',action: 'ajaxAudioList')}",
                    "fnRowCallback": function (nRow, aData, iDisplayIndex) {
                        if (aData.DT_RowId == undefined) {
                            return true;
                        }
                        $('td:eq(5)', nRow).html(getActionBtn(nRow, aData));
                        return nRow;
                    },
                    "aoColumns": [
                        null,
                        { "bSortable": false },
                        { "bSortable": false },
                        { "bSortable": false },
                        { "bSortable": false },
                        { "bSortable": false }
                    ]
                });

                $('#example').on('click', 'a.delete-reference', function (e) {
                    var selectRow = $(this).parents('tr');
                    var confirmDel = confirm("Are you sure?");
                    if (confirmDel == true) {
                        var control = this;
                        var referenceId = $(control).attr('referenceId');
                        jQuery.ajax({
                            type: 'POST',
                            dataType: 'JSON',
                            url: "${g.createLink(controller: 'audio',action: 'deleteRow')}?id=" + referenceId,
                            success: function (data, textStatus) {
                                $('#example').DataTable().ajax.reload();
                                alert("Deleted successfully");
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                            }
                        });
                    }
                    e.preventDefault();
                });
                $('#example').on('click', 'a.inactive-reference', function (e) {
                    //ajax code for Inactive row
                    e.preventDefault();
                });

                $('#example').on('click', 'a.edit-reference', function (e) {
                    //ajax code for edit row
                    e.preventDefault();
                });
        });
    function getActionBtn(nRow, aData) {
        var actionButtons = "";
        actionButtons += '<span class="col-md-4 no-padding"><a href="" referenceId="' + aData.DT_RowId + '" class="inactive-reference" title="Change Status">';
        actionButtons += '<span class="glyphicon glyphicon-retweet"></span></a></span>';
        actionButtons += '<span class="col-md-4 no-padding"><a href="" referenceId="' + aData.DT_RowId + '" class="edit-reference" title="Edit">';
        actionButtons += '<span class="glyphicon glyphicon-edit"></span></a></span>';
        actionButtons += '<span class="col-md-4 no-padding"><a href="" referenceId="' + aData.DT_RowId + '" class="delete-reference" title="Delete">';
        actionButtons += '<span class="glyphicon glyphicon-remove"></span></a></span>';
        return actionButtons;
}

In your controller, you will need two action. 在您的控制器中,您将需要执行两个操作。 The index action will initially load the page with data table ( and 10 row if exist) and a list action that will use for pagination. index动作最初将为页面加载数据表(如果存在则为10行)和将用于分页的list动作。

class AudioController {

def audioService

def index() {
    LinkedHashMap resultMap = audioService.audioPaginateList(params)

    if (!resultMap || resultMap.totalCount == 0) {
        render(view: 'your_view_page', model: [dataReturn: null, totalCount: 0])
        return
    }
    int totalCount = resultMap.totalCount
    render(view: 'your_view_page', model: [dataReturn: resultMap.results, totalCount: totalCount])
}

def ajaxAudioList() {
    LinkedHashMap gridData
    String result
    LinkedHashMap resultMap =audioService.audioPaginateList(params)

    if(!resultMap || resultMap.totalCount== 0){
        gridData = [iTotalRecords: 0, iTotalDisplayRecords: 0, aaData: []]
        result = gridData as JSON
        render result
        return
    }
    int totalCount =resultMap.totalCount
    gridData = [iTotalRecords: totalCount, iTotalDisplayRecords: totalCount, aaData: resultMap.results]
    result = gridData as JSON
    render result
}
//other controller actions

Finally add the audioService class in your service 最后在您的服务中添加audioService类

class AudioService {
static transactional = false

static final String[] sortColumns = ['id','title','shortDesc']
LinkedHashMap audioPaginateList(GrailsParameterMap params){
    int iDisplayStart = params.iDisplayStart ? params.getInt('iDisplayStart') : 0
    int iDisplayLength = params.iDisplayLength ? params.getInt('iDisplayLength') : 10
    String sSortDir = params.sSortDir_0 ? params.sSortDir_0 : 'desc'
    int iSortingCol = params.iSortCol_0 ? params.getInt('iSortCol_0') : 0
    //Search string, use or logic to all fields that required to include
    String sSearch = params.sSearch ? params.sSearch : null
    if (sSearch) {
        sSearch = "%" + sSearch + "%"
    }
    String sortColumn = getSortColumn(sortColumns,iSortingCol)
    List dataReturns = new ArrayList()
    def c = Audio.createCriteria()
    def results = c.list(max: iDisplayLength, offset: iDisplayStart) {
        and {
            //eq("activeStatus", ActiveStatus.ACTIVE)

        }
        if (sSearch) {
            or {
                ilike('title', sSearch)
                ilike('shortDesc', sSearch)
            }
        }
        order(sortColumn, sSortDir)
    }
    int totalCount = results.totalCount
    if (totalCount > 0) {
        String status
        results.each { Audio audioInstance ->
            if(audioInstance.isActive){
                status = "Active"
            }else {
                status = "Inactive"
            }
            dataReturns.add([DT_RowId: audioInstance.id, 0: audioInstance.title, 1: audioInstance.shortDesc,2: audioInstance.streamType,3: audioInstance.downloadCount, 4: status, 5:''])
        }
    }
    return [totalCount:totalCount,results:dataReturns]
}

public String getSortColumn(String [] sortColumns, int idx){
    if(!sortColumns || sortColumns.length<1)
        return 'id'
    int columnCounts = sortColumns.length
    if(idx>0 && idx<columnCounts){
        return sortColumns[idx]
    }
    return sortColumns[0]
}

} }

Wish it will help you 希望对您有帮助

I have solved the issue don't know is right or wrong but worked for me. 我已经解决了不知道对与错但为我工作的问题。 I just skip the pagination in grails cause data-table is doing it. 我只是跳过了分页,因为数据表正在这样做。 So I have changed the index in controller and it works fine. 所以我改变了控制器中的索引,它工作正常。 The changes are as follows :: 更改如下:

def audioInstanceList = Audio.getAll()
    [audioInstanceList: audioInstanceList]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM