用JSON填充DataTable时,需要在一个列中呈现一个超链接,并在另一个JSON字段中找到一个值

Populating a DataTable with JSON, need to render a hyperlink in one column with a value found in a different JSON field

本文关键字:一个 JSON 超链接 字段 另一个 DataTable 填充      更新时间:2023-09-26

我有一个样本json对象的数据:

[ 
    {
        "id": 1,
        "title": "Fred",
        "author": "Flintstone"
    }, {
        "id": 2,
        "title": "Fred",
        "author": "Flintstone"
    }, {
        "id": 3,
        "title": "Fred",
        "author": "Flintstone"
    }.....
HTML

<table class="table" id="tblRunbook">
                                            <thead>
                                                <tr>
                                                    <th width="60px">ID</th>
                                                    <th width="300px">Title</th>
                                                    <th width="200px">Author</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            </tbody>
                                        </table>
JavaScript:

   $(document).ready(function() {
        $('#tblRunbook').dataTable({
            <!-- Retrieve a static json file, you could also have a URL to a controller method. -->
            "sAjaxSource" : "/getRunbooks",
            "sAjaxDataProp": "",
            <!-- Indicate to dataTable what the field names are we want, in the order we want them in the table. -->
            "aoColumns": [
                          {"data": "id"},
                          {"data": "title",
                             "render": function ( data, type, row, meta ) {
                                return '<a href="runbook?rbID=" + data.id + '>' + data + '</a>';}
                          },
                          {"data": "author"}
                ]

        });
    });

包含ID的列将被隐藏,但我想将链接设置为runbook?rbID = ID。我想访问JSON对象中的前一个字段,在本例中是"data" : "id",并将其设置在函数返回'<a href="runbook?rbID=" + data.id + '>'的第二个字段中,其中data.idID

我找到了一个解决办法。

var runbookID;

        "aoColumns": [
                      {"data": function(data, type, row, meta){
                          runbookID = data.id;
                          return data.id;}
                      },
                      {"data": "title",
                         "render": function ( data, type, row, meta ) {
                            return "<a href='runbook?rbID=" + runbookID + "'>" + data + '</a>';}
                      },
                      {"data": "author"}
            ]