2011-12-27 88 views
5

Cada fila en la tabla de datos tiene un botón de borrar.Cómo actualizar la tabla de datos de jquery después de eliminar una fila

al hacer clic con el botón de borrar, llamo este código:

$('.deleteButton').live('click', function() { 

      var $this = $(this); 
      var url = $this.attr("id"); 
      $("#example").fnReloadAjax(); 
      $.getJSON(url, Success()); 
     }); 

La url es la acción del controlador que tiene el ID y borra los datos de la base de datos. Eso funciona. Ahora quiero llamar a la función de actualización/redibujado de la tabla de datos para que pueda cargar nuevos resultados pero no funciona.

Datatable es:

$("#example").dataTable({ 
      "aoColumns": [ 
        { "sTitle": "Id" }, 
         { "sTitle": "Name" }], 


      "bProcessing": true, 
      "bServerSide": true, 

      "sAjaxSource": '@Url.Action("FetchData", "Home")', 
      "sPaginationType": "full_numbers", 

}); 

Puede alguien por favor consejo?

Respuesta

9

citado del API datatable page - en el fnReloadAjax() bala:

Nota: Para volver a cargar los datos cuando se utiliza el procesamiento del lado del servidor, sólo tiene que utilizar el incorporado en función de la API fnDraw en lugar de este plug-in.

Por lo tanto, probablemente sea mejor que use fnDraw.

[EDIT] En realidad, el orden de las llamadas debe ser:

// you don't have to use $.json because you don't use the downloaded data 
// first, ask the server to delete the data 
$.ajax({ 
    url: urlToDelete, 
    success: function() { 
     // if it worked, ask datatable to redraw the table with the new data 
     $("#example").dataTable().fnDraw(); 
     // if this js function does anything useful (like deleting the row), then call it: 
     Success(); 
    }, 
    error: function() { 
     // display any error (like server couldn't be reached...), or at least try to log it 
    } 
}); 
+0

Quiero llamar a la función de borrado de lado del servidor. ¿Hay una mejor manera de llamar a esa acción? – InfoLearner

+0

, entonces, debe llamarlo * antes * pidiendo un redibujado. Voy a editar mi respuesta para que sea más clara – JMax

+0

como antes, puede entrar en la función de éxito pero no actualiza la tabla de datos? – InfoLearner

1

La respuesta aquí no funcionó para mí, así que usa esto:

http://datatables.net/plug-ins/api#fnReloadAjax

Añadir este a un archivo:

$.fn.dataTableExt.oApi.fnReloadAjax = function (oSettings, sNewSource, fnCallback, bStandingRedraw) 
{ 
    if (sNewSource !== undefined && sNewSource !== null) { 
     oSettings.sAjaxSource = sNewSource; 
    } 

    // Server-side processing should just call fnDraw 
    if (oSettings.oFeatures.bServerSide) { 
     this.fnDraw(); 
     return; 
    } 

    this.oApi._fnProcessingDisplay(oSettings, true); 
    var that = this; 
    var iStart = oSettings._iDisplayStart; 
    var aData = []; 

    this.oApi._fnServerParams(oSettings, aData); 

    oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) { 
     /* Clear the old information from the table */ 
     that.oApi._fnClearTable(oSettings); 

     /* Got the data - add it to the table */ 
     var aData = (oSettings.sAjaxDataProp !== "") ? 
      that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json; 

     for (var i=0 ; i<aData.length ; i++) 
     { 
      that.oApi._fnAddData(oSettings, aData[i]); 
     } 

     oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); 

     that.fnDraw(); 

     if (bStandingRedraw === true) 
     { 
      oSettings._iDisplayStart = iStart; 
      that.oApi._fnCalculateEnd(oSettings); 
      that.fnDraw(false); 
     } 

     that.oApi._fnProcessingDisplay(oSettings, false); 

     /* Callback user function - for event handlers etc */ 
     if (typeof fnCallback == 'function' && fnCallback !== null) 
     { 
      fnCallback(oSettings); 
     } 
    }, oSettings); 
}; 

Incluya el archivo en su página y llame al como esto:

// Example call to load a new file 
oTable.fnReloadAjax('media/examples_support/json_source2.txt'); 

// Example call to reload from original file 
oTable.fnReloadAjax(); 
3

Pude resolver este problema con un enfoque mucho más simple que el proporcionado en las respuestas anteriores.

Ajax llamada para borrar los datos de back-end

En primer lugar borrar los datos de backend usando normal de llamada AJAX asíncrona.

Borrar de la tabla de datos frontend

Obtener el TR fila que desea borrar y utilizar la función de tabla de datos fnDeleteRow eliminar esta fila. Esto actualizará automáticamente la tabla para que no necesite fnDraw u otras cosas.

//in my case its delete button which was clicked 
//so I got its parents parent which is TR row 
var row = $(this).parent().parent(); 


$('DATA TABLE SELECTOR').dataTable().fnDeleteRow(row); 

y ya está .. :-)

+0

mejor ... funcionó para mí – MKD

0

Uso instancia de dataTable y quitar la fila de tabla de datos

dataTable.fnDeleteRow($(that).closest('tr').remove()); 
dataTable.fnDraw(); 
Cuestiones relacionadas