在Datatables中加入错误提示功能

经常用Datatables的童鞋一定碰到过当采用服务端请求的时候,一旦后台出现异常,Datatables的会一直卡在那里,中间的正在处理的提示一直停留着。 

为了能给用户更好的体验,需要对Datatables进行扩展和自定义错误处理函数。 

首先到Datatables官网获取一个插件: 
http://datatables.net/plug-ins/api 

jQuery.fn.dataTableExt.oApi.fnProcessingIndicator = function ( oSettings, onoff )
{
    if( typeof(onoff) == 'undefined' )
    {
        onoff=true;
    }
    this.oApi._fnProcessingDisplay( oSettings, onoff );
};

该插件用于开启或关闭Datatables的正在处理提醒的消息框。 
使用方法: 

oTable.fnProcessingIndicator();      // On
oTable.fnProcessingIndicator(false); // Off

修改datatables创建时的options选项: 

Javascript代码 
"fnServerData": function ( sSource, aoData, fnCallback ) {
    $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": sSource,
        "data": aoData,
        "success": fnCallback,
        "timeout": 15000,   // optional if you want to handle timeouts (which you should)
        "error": handleAjaxError // this sets up jQuery to give me errors
    } );
},

定义处理错误的函数: 

Javascript代码
function handleAjaxError( xhr, textStatus, error ) {
    if ( textStatus === 'timeout' ) {
        alert( 'The server took too long to send the data.' );
    }
    else {
        alert( 'An error occurred on the server. Please try again in a minute.' );
    }

    $('.dataTable').dataTable().fnProcessingIndicator( false );
}
原文地址:https://www.cnblogs.com/hubing/p/4692044.html