DataTables在加载AJAX数据时通知加载时间

时间:2017-10-31 15:29:48

标签: javascript jquery ajax datatable datatables

我有一些表开始为空,DataTables请求WebServer获取数据。

可以花一些时间来加载它。 DataTables显示默认的加载消息。但我想添加一个计数器来通知加载运行的时间,而不是简单的加载文本或一些古怪的动画。

我找不到在文档中执行此操作的方法。有可能吗?

更新:MonkeyZeus的答案非常有效。这是我的最终代码:

// ...
,dataTablesLoading: function(e, settings, processing ){
    setTimeout(function(){
        var targetJs = e.target;
        var target = $(targetJs);
        var timerContainer = target.find('.dataTables_empty');
//tlog(targetJs,'targetJs');
//tlog(target,'target');
//tlog(timerContainer,'timerContainer');

        if(processing){
                var timer = 0;
                var timerHandler = setInterval(function(){
                    timer++;
                    var hours = Math.floor(timer/3600);
                    var minutes = Math.floor((timer-(hours*60))/60);
                    var secs = timer-(hours*3600)-(minutes*60);

                    var timerText = hours+':'+minutes.lpad("0",2)+':'+secs.lpad("0",2);
tlog(timerText,'timerText');
//tlog(timerContainer,'timerContainer');
                    timerContainer.text("Loading... "+timerText);
                },1000);


            targetJs.setAttribute("data-loading-timer",timerHandler);
tlog(timerHandler,'timerHandler processing');
        }else{
            var timerHandler = parseInt(targetJs.getAttribute("data-loading-timer"));
tlog(timerHandler,'timerHandler not processing');

            if(timerHandler>0)
                clearInterval(timerHandler);
        }

    },1000);
}
// ...
$('#...')
    .on( 'processing.dt', Framework.utils.dataTablesLoading )
    .DataTable({...})

1 个答案:

答案 0 :(得分:1)

First, you will need to enable processing when invoking the datatable:

$('#example').dataTable( {
    "processing": true
} );

Next, you will need to declare what happens instead of the default Loading message using the dt namespace's processing event listener:

// This event will fire twice so pay attention to the processing parameter
$('#example').on( 'processing.dt', function ( e, settings, processing ) {
    if( processing  === true ) {
        alert('Hey, we are processing!');
        // some custom code which targets #processingIndicator and applies some timer plug-in or whatever; you figure it out.
    }
    else {
        alert('Hey, we are done processing!');
        // some custom code which targets #processingIndicator and hides it; you figure it out.
    }
} )
.dataTable();

此外,长时间加载需要考虑UX方面,因此如果您想要获得更好的体验,请务必查看https://ux.stackexchange.com/a/80858/45170