问题
I'm using the Datatables plugin to get table data from a server using the ajax Property and transform it using the dataSrc property. My datatables definition:
var my_table = $('#my_table').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/my/url",
"type": "POST",
"dataSrc": function(json) {
console.log('json', json);
return format_my_table_data(json.data);
}
},
"deferLoading": found_rows,
"data": initial_my_table_data,
"ordering": true,
"order": [[1, "desc"]],
"lengthMenu": [
[25, 50, 100],
[25, 50, 100]
],
"columns": my_table_columns
});
The initial load works fine, and ordering columns and searching works sometimes but mostly I see the ajax call return successfully with valid json (I verified using jsonlint.com) and the table is stuck at "Processing..." sometimes or the table just doesn't change at all.
Json from the server:
{"recordsTotal":379,"recordsFiltered":378,"draw":25,"data":[{...}]}
When inspecting the network in the console i can see the ajax request being sent and a response that is similar each time (with a total time between 600ms and 1600ms depending on the number of rows returned) but my console.log inside the dataSrc function isn't called and no javascript errors in the console. What gives?
回答1:
Your script should return draw
parameter with the same value of the draw
parameter in the request. I believe it starts at 1
and then increments with every request.
From the manual:
draw
The draw counter that this object is a response to - from the
draw
parameter sent as part of the data request. Note that it is strongly recommended for security reasons that you cast this parameter to an integer, rather than simply echoing back to the client what it sent in thedraw
parameter, in order to prevent Cross Site Scripting (XSS) attacks.
来源:https://stackoverflow.com/questions/39478730/datatables-datasrc-function-not-called-on-successful-ajax-response