如何将REST调用JSON响应附加到jQuery数据表?

Sli*_*ick 2 jquery jquery-plugins datatables

我想显示的jQuery的REST调用JSON响应数据表.

以下是我收到的JSON响应.

{
    "artifact": [
        {
            "artifactId": "I8cc4a96ef69a11e08b448cf533780ea2",
            "batchId": "15581",
            "processId": "115458787"
        },
        {
            "artifactId": "e08b448cf533780ea2I8cc4a96ef69a11",
            "batchId": "14962",
            "processId": "787974254"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

剧本:

<script type="text/javascript">
        $(document).ready(function () {
            $("#artifacts").dataTable({
                "sPaginationType": "full_numbers",
                "bJQueryUI": true
            });
        });
        function submitForm()
        {
            $.getJSON('http://myurl.com/JerseySample/rest/search', function(data) {
                $.each(data.artifact, function(i,artifact){
                        $('#artifacts').datatable().fnAddData([
                                artifact.artifactId,
                                artifact.batchId,
                                artifact.processId ]
                                );
                });
             });
        }
</script>
Run Code Online (Sandbox Code Playgroud)

HTML:

<form class="searchform">
        <input class="searchfield" type="text" /> 
        <input class="searchbutton" type="button" value="Go" id="go" onclick="submitForm()" /> 

</form>
    <div id="container">
        <div id="demo_jui">
            <table id="artifacts" class="display">
                    <thead>
                            <tr>
                                <th>Artifact Id</th>
                                <th>Batch Id</th>
                                <th>Legacy Id</th>
                            </tr>
                    </thead>
                    <tbody>
                    </tbody>
            </table>
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

有人能解释为什么我无法将JSON响应加载到datatable中吗?有没有更好的方法来获得此功能?

Sha*_*ter 5

你做的一切都是正确的,你只是做了一个菜鸟错误,很容易错过.

当你这样做

$("#artifacts").dataTable();
Run Code Online (Sandbox Code Playgroud)

您正在创建一个新的数据表实例.Datatables在该调用上返回对象实例(带有API函数),但是您没有将该实例存储在任何地方,因此,您将丢失对刚刚创建的数据表的所有引用.

要解决此问题,只需添加对您创建的数据表的引用即可

var thisTable = $("#artifacts").dataTable(
    {
        "sPaginationType": "full_numbers",
        "bJQueryUI": true
    }
);
Run Code Online (Sandbox Code Playgroud)

然后在你的每个函数中引用它

$.each(data.artifact, function(i,artifact){
    thisTable.fnAddData(
        [
            artifact.artifactId,
            artifact.batchId,
            artifact.processId 
        ]
    );
 });
Run Code Online (Sandbox Code Playgroud)

这是一个JSFiddle示例,可以看到它的实际运行情况.

动态添加新行例如在datatables.net是比较差的,因为它做,而不需要添加引用内嵌API调用.在以下关于多重过滤的示例中更好地展示了它.

您还可以在他们的API文档中阅读它.
提示:它在第一行中展示$