2017-09-04 2 views
0

J'ai l'initialisation suivante pour plusieurs tables avec la même classe, mais différents attributs id:Comment obtenir l'ID de la table actuelle à ajouter aux données ajax lorsque l'initialisation est utilisée pour plusieurs tables?

var $table = $('table.jobs'); 

$table.DataTable({ 

    .... 
    ajax: { 
     url: '/my-url', 
     dataSrc: function (json) { 

      return json.data 
     }, 
     data: function(data) { 

      data.table_id = $table.attr('id'); 
      // gives the same id for all tables 

     } 
    }, 
    ... 
}); 

Est-il possible que je peux identifier quelle table envoie la demande ajax? J'essaie d'éviter de dupliquer toute l'initialisation pour chaque table.

Répondre

1

Vous pouvez essayer quelque chose comme ceci:

$('.table.jobs').each(function() { 
    $('#'+$(this).attr('id')).dataTable({ 
     url: '/my-url', 
    dataSrc: function (json) { 

     return json.data 
    }, 
    data: function(data) { 

     data.table_id = $table.attr('id'); 
     // gives the same id for all tables 

    } 
}); 
+0

ah, parfait, merci! J'aurais dû penser à cela :) – martincarlin87