jQuery datatables ajax callback
I am using jQuery DataTables and doing server-side data. I'm trying to call a function when the ajax call returns. I tried inserting this fnCallback2
which calls my function and the original function, but jQuery just throws an error (and doesn't tell me what the error is) and skips out.
$("#brands").dataTable( {
"bServerSide" : true,
"sAjaxSource" : "ajax.php",
"fnServerData" : function(sSource, aoData, fnCallback) {
fnCallback2 = function(a,b,c){
fnCallback.call(a,b,c);
update_editable();开发者_JAVA百科
};
$.ajax( {
"dataType" : 'json',
"type" : "POST",
"url" : sSource,
"data" : aoData,
"success" : fnCallback2
});}});
I also tried adding the fnInitComplete
parameter, but that only gets called the first time, not after subsequent pages.
"fnInitComplete": function(){
update_editable();
},
How do I correctly call my code after the ajax request so that the original callback gets called as well?
Another option is to use the fnDrawCallback that is called after each draw event. Which will be done after every ajax request.
"fnDrawCallback" : function() {
update_editable();
}
SOLUTION
With DataTables 1.10 there are multiple ways to handle Ajax completion event.
Using
ajax.dataSrc
option:var table = $("#example").DataTable({ serverSide: true, ajax: { url: "/test/0", dataSrc: function(d){ // TODO: Insert your code return d.data; } } });
Using
xhr
event:$("#example").on('xhr.dt', function(e, settings, json, xhr){ // TODO: Insert your code }); var table = $("#example").DataTable({ serverSide: true, ajax: { url: "/test/0" } });
There is one extra advantage to using xhr
event versus ajax.dataSrc
option:
As of DataTables 1.10.7 this event is triggered by both success and error conditions when the Ajax request completed (i.e. it is always triggered regardless of the outcome of the Ajax request).
DEMO
See this jsFiddle for code and demonstration.
Try this way :
"fnServerData": function ( sSource, aoData, fnCallback ) {
/* Add some extra data to the sender */
aoData.push( { "name": "more_data", "value": "my_value" } );
$.ajax( {
"dataType" : 'json',
"type" : "POST",
"url" : sSource,
"data" : aoData,
"success" : function(json) {
/* Do whatever additional processing you want on the callback,
then tell DataTables */
fnCallback(json)
} );
}
You can then do what ever you want to do before the fnCallback(json);
line - including calling a function.
Try This:
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
fnCallback(json)
}).complete(function(){update_editable(););
}
精彩评论