經常用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選項:
"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 } ); },
定義處理錯誤的函數:
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 ); }