通过AJAX调用定期加载DataTable

时间:2012-11-30 14:30:03

标签: jquery jquery-datatables

以下是我的代码:

(function worker() {
oTable = $('#example').dataTable({"iDisplayLength" : 25, "sAjaxSource": "/getservicevers/?value=" + QueryString.stage ,"bDestroy" : true ,  "fnServerData" :
                function ( sSource, aoData, fnCallback ) {
                        $.ajax( {
                                 "dataType": 'json',
                                "type": "GET",
                                "url": sSource,
                                "async":false,
                                "success": function (json)
                                {
                                        fnCallback(json);
                                },
                                complete: function() {
                                setTimeout(worker, 5000);
                                }
                        })
                }
                });
        })();

在UI方面,我确实看到定期生成AJAX请求,但问题是DataTables仅在浏览器中第一次完美加载(宽度/大小):

Show                                                                                                                                                                                                 Search

XXXXXX                                          XXXXXXXXXXXXX                             XXXXXXXXXXXX                                XXXXXXXXXXXXXX


Showing ...                                                                                                                                                                                        Prev / Next

第二次收到AJAX响应后,DataTables缩小了:

Show                                                                                                                                                                                                 Search

                                                                                  XXXXX    XXXX  XXXXX    XXXX


Showing ...                                                                                                                                                                                        Prev / Next

请注意标签和数据是正确的,但只是表格缩小了 - 请帮助解决问题

提前致谢。

==================================== UPDATE ========== ============================

我尝试了以下代码:

oTable = $('#example').dataTable();
(function worker() {
                        $.ajax( {
                                "dataType": 'json',
                                "type": "GET",
                                "url": "/getservicevers/?data=" + QueryString.data,
                                "async":false,
                                "success": function (data)
                                {
                                        alert("myObject is " + data.toSource());
                                        alert(data.aaData[0][0]);
                                        oTable.fnClearTable();
                                        for(var i = 0; i < data.length; i++) {
                                            oTable.fnAddData([
                                                data.aaData[i][0],
                                                data.aaData[i][1],
                                                data.aaData[i][2]
                                        ]);
                                }
                                },
                                complete: function() {
                                        oTable.fnDraw();
                                        setTimeout(worker, 5000);
                                }
                });
        })();

AJAX调用成功方法中前两个警告语句的输出是:

myObject is ({iTotalRecords:1, iTotalDisplayRecords:1, aaData:[[" data1", " data2", " data3"]]})
data1

代码工作正常但在页面中我没有在数据表中看到任何数据而是:

Show                                                                                                                                                                                                 Search

    XXXXXX                                          XXXXXXXXXXXXX                             XXXXXXXXXXXX                                XXXXXXXXXXXXXX

                                         No data available in table    
    Showing ...                                                                                        

我需要进一步解决这个问题,并注意到在发出AJAX请求时我没有看到“正在加载...”文本。以下是我的完美代码:

<!DOCTYPE html>
<html>

<head>
        <title>My Details</title>
        <meta charset='UTF-8' />
        <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" />
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
        <script>
        $(document).ready(function() {
        var QueryString = function () {
                                                  var query_string = {};
                                                  var query = window.location.search.substring(1);
                                                  var vars = query.split("&");
                                                  for (var i=0;i<vars.length;i++) {
                                                    var pair = vars[i].split("=");
                                                    if (typeof query_string[pair[0]] === "undefined") {
                                                      query_string[pair[0]] = pair[1];
                                                    } else if (typeof query_string[pair[0]] === "string") {
                                                      var arr = [ query_string[pair[0]], pair[1] ];
                                                      query_string[pair[0]] = arr;
                                                    } else {
                                                      query_string[pair[0]].push(pair[1]);
                                                    }
                                                  }
                                                    return query_string;
                                          } ();
        /* Add the events etc before DataTables hides a column */
        $("thead input").keyup( function () {
                /* Filter on the column (the index) of this element */
                oTable.fnFilter( this.value, oTable.oApi._fnVisibleToColumnIndex(
                        oTable.fnSettings(), $("thead input").index(this) ) );
        } );

        /*
         * Support functions to provide a little bit of 'user friendlyness' to the textboxes
         */
        $("thead input").each( function (i) {
                this.initVal = this.value;
        } );

        $("thead input").focus( function () {
                if ( this.className == "search" )
                {
                        this.className = "";
                        this.value = "";
                }
        } );

        $("thead input").blur( function (i) {
                if ( this.value == "" )
                {
                        this.className = "search";
                        this.value = this.initVal;
                }
        } );
        oTable = $('#example').dataTable();
        (function worker() {
                                $.ajax( {
                                        "dataType": 'json',
                                        "type": "GET",
                                        "url": "/getservicevers/?data=" + QueryString.data,
                                        "async":false,
                                        "success": function (data)
                                        {
                                                alert("myObject is " + data.toSource());
                                                alert(data.aaData[0][0]);
                                                oTable.fnClearTable();
                                                for(var i = 0; i < data.length; i++) {
                                                    oTable.fnAddData([
                                                        data.aaData[i][0],
                                                        data.aaData[i][1],
                                                        data.aaData[i][2]
                                                ]);
                                        }
                                        },
                                        complete: function() {
                                                oTable.fnDraw();
                                                setTimeout(worker, 5000);
                                        }
                        });
                })();
                } );
        </script>
</head>
<body>
        <table id="example">
        <thead>
                <tr>
                        <th>Data1</th>
                        <th>Data2</th>
                        <th>Data3</th>
                </tr>
        </thead>
        <tfoot>
                <tr>
                        <th>Data1</th>
                        <th>Data2</th>
                        <th>Data3</th>
                </tr>
        </tfoot>
        <tbody>
        </tbody>
        </table>
</body>

</html>

通过以下网址从浏览器访问的页面:

http://mybox.com/mon.html?data=test

1 个答案:

答案 0 :(得分:1)

你的功能看起来很简单,所以我想知道这是否是由浏览器引起的图形故障。添加oTable.fnDraw();可能会有所帮助。

或者,如果您的AJAX调用返回整个数据集,则可以先使用oTable.fnClearTable();清除表格,然后通过循环DataTable's .fnAddData() method来更改将数据添加到表格中的方式。< / p>

$.ajax({
    url: '/getservicevers/?value=" + QueryString.stage',
    type: 'post',
    data: data, // this would be an array
    success: function(data) {
        oTable.fnClearTable();
        // populate the table with data
        for(var i = 0; i < data.length; i++) {
            oTable.fnAddData([
                data[i].column1,
                data[i].column2,
                data[i].column3
            ]);
        }
    }
});