2016-04-25 36 views
0

我正在使用jQuery Datatable來顯示數據庫中的數據。我正在使用ajax來獲取數據。所以情況就像我有引導標籤。所以當用戶點擊任何標籤時,它將顯示與該標籤對應的數據。所以我的jQuery代碼是這樣的jQuery ajax datatable在某些時刻顯示舊數據一段時間?

$('a.communication-data[data-toggle="tab"]').on('click', function(e) { 
    $('#get_communication').dataTable().fnDestroy();  
    var proj_id = $('input#user_project_id').val(); 
    var communicationTable = $('#get_communication').dataTable(); 
    $('#get_communication').dataTable({ 
     "processing": true, 
     "serverSide": true, 
     "bDestroy": true, 
     "iDisplayLength" : trans.show_rows, 
     "ajax": ajaxUrl+"?action=get_communication_history&proj_id="+proj_id, 
     language: { 
      searchPlaceholder: "Search.." 
     }  
    }); 
}); 

這裏的數據表顯示幾秒鐘舊數據和它顯示的第一次實際數據之後。當用戶再次檢查沒有頁面重新加載的標籤時,它顯示正確的數據。 那麼有人可以告訴我爲什麼會發生這個問題嗎?如何解決這個問題?任何幫助和建議都將非常可觀。謝謝

+0

什麼是DataTable的Ajax調用 –

+1

也許你的請求沒有從服務器返回之前的內容,同時請求被處理後你仍然可以看到舊的數據? – Justinas

+0

@VelimirTchatchevsky在Ajax調用之前沒有設置內容。 – NewUser

回答

0

我查了資料,並得到了一些方法,如fnDrawCallbackfnPreDrawCallback。還有一個example真的幫了我。

所以最後我的代碼是這樣的

$('a.communication-data[data-toggle="tab"]').on('click', function(e) { 
    $('#get_communication_history').dataTable().fnDestroy(); 
    var proj_id = $('input#user_project_id').val(); 
    $('#get_communication_history').dataTable({ 
     "processing": true, 
     "fnPreDrawCallback": function() { 
      showMessage(); 
     return true; 
     }, 
     "fnDrawCallback": function() { 
     hideOverlay(); 
     },    
     "serverSide": true, 
     "bDestroy": true, 
     "iDisplayLength" : trans.show_rows, 
     "ajax": ajaxUrl+"?action=get_communication_history&proj_id="+proj_id, 
     "language": { 
      "searchPlaceholder": "Search..", 
     }  
    }); 
}); 

function showMessage() { 
    $('table#get_communication_history > tbody').html(""); 
    parentHtml = $('<tr><td colspan="5"><div class="communication-history-loading" style="text-align: center; font-weight: bold;">Please wait! Getting communication history..</div></td></tr>'); 
    $('table#get_communication_history tbody').html(parentHtml); 
} 

function hideOverlay() { 
    parentHtml = $('<tr><td colspan="5"><div class="communication-history-loading" style="text-align: center; font-weight: bold;">Please wait! Getting communication history..</div></td></tr>'); 
    $('table#get_communication_history > tbody').remove(parentHtml); 
} 
0

Ajax請求將需要一些時間在服務器上處理並返回。

你可以使用一些加載器來表明數據加載:

$('a.communication-data[data-toggle="tab"]').on('click', function(e) { 
    // Indicate that you are loading data 
    $('#get_communication').html('<tr><td>Loading...</td></tr>'); 

    // now do Ajax call 
} 
+0

如何在Ajax響應時刪除加載內容? – NewUser

+0

@NewUser它應該覆蓋當前的表格內容。 – Justinas

+0

不要這樣做。我測試了代碼。即使在ajax響應後顯示裝載機行 – NewUser