Skip to main content
 首页 » 编程设计

jquery之如何将 jQuery DataTables 导入 Grails 2.4.4

2026年07月28日4lvdongjie

我有一个 Grails 2.4.4 应用程序,并且正在尝试实现一个利用 jQuery DataTable 的 GSP。 。我看到有一个旧 DataTable plugin但它看起来没有维护并且与 Grails 2.x 不兼容。更不用说,应该有一种方法可以简单地将任何 JS 库包含在 Grails 中,而无需明确要求插件。

这是我的 BuildConfig 的 plugins 部分:

plugins { 
    build ":release:3.0.1" 
    build ":tomcat:7.0.52.1" 
 
    compile "org.grails.plugins:gson:1.1.4" 
    compile ":rest-client-builder:1.0.3" 
    compile ":yammer-metrics:3.0.1-2" 
 
    runtime ":jquery:1.11.1" 
    runtime ":cached-resources:1.0" 
    runtime ":resources:1.2.14" 
    compile ":cache-headers:1.1.7" 
 
    compile ":rest-client-builder:1.0.3" 
    compile ":export:1.6" 
    compile ":standalone:1.2.3" 
    compile ":cache-headers:1.1.7" 
    compile ":scaffolding:2.1.2" 
    compile ':cache:1.1.3' 
 
    runtime ":resources:1.2.14" 
    runtime ":hibernate:3.6.10.15" 
    runtime ":database-migration:1.4.0" 
    runtime ":jquery:1.11.1" 
} 

出于本问题范围之外的原因,我无法删除或更改plugins部分中的任何现有声明,但我可以添加它们。我听说一种称为“ Assets 管道”的东西是将 JS 库添加到 Grails 应用程序的一种新的很酷的方法,但我能找到的有关该管道的所有文献都是模糊且高级的。我找不到任何使用此管道将 DataTables 包含在 Grails 应用程序中的实际示例。

DataTable 的“Hello World!”版本似乎是这样的:

<table id="example" class="display" cellspacing="0" width="100%"> 
    <thead> 
        <tr> 
            <th>Name</th> 
            <th>Position</th> 
            <th>Office</th> 
        </tr> 
    </thead> 
 
    <tbody> 
        <tr> 
            <td>Tiger Nixon</td> 
            <td>System Architect</td> 
            <td>Edinburgh</td> 
        </tr> 
 
        ...lots of more rows 
    </tbody> 
</table> 
 
$(document).ready(function() { 
    $('#example').DataTable(); 
} ); 

所以我问:如何让(上面的)“Hello World”数据表在 GSP 中运行?我需要什么特定配置、插件等连接起来使这项工作正常进行?

请您参考如下方法:

如果您的 DataTable js 文件保存在此目录 web-app\js 中,您可以在需要 DataTable 的 View 中使用此 Grails 标记。

<g:javascript src="jquery.datatables.min.js" /> 

同样,您可以获得所需的css文件

<g:external dir="css" file="jquery.datatables.css" /> 

加载所需文件后,您可以调用 jQuery 函数

<g:javascript> 
    $(document).ready(function() { 
        $('#example').DataTable(); 
    } ); 
</g:javascript>