I'm using a jquery datatable which is loading some JSON dynamically using the sAjaxSource
property. Everything's fine, except that the loaded content is being treated as potential markup, so things go strange if text in cells contains <
or somesuch.
How can I get datatables to escape my data before loading it into the table? I don't want to do it server side because the server shouldn't care what the client's going to do with the data.
I'm using a jquery datatable which is loading some JSON dynamically using the sAjaxSource
property. Everything's fine, except that the loaded content is being treated as potential markup, so things go strange if text in cells contains <
or somesuch.
How can I get datatables to escape my data before loading it into the table? I don't want to do it server side because the server shouldn't care what the client's going to do with the data.
Share Improve this question edited Oct 13, 2011 at 16:10 Greg Pettit 10.8k5 gold badges57 silver badges73 bronze badges asked Oct 12, 2011 at 13:08 kdtkdt 28.5k34 gold badges95 silver badges143 bronze badges 1- Try this technique: stackoverflow./questions/24816/… – rcravens Commented Oct 12, 2011 at 13:12
2 Answers
Reset to default 5[note: the following answer is for DataTables 1.9x and below. 1.10 changed the method naming conventions and a few other things. 1.9x methods are available but deprecated and will inevitably be stripped out pletely.]
If it's safe to strip them "wholesale" (ie. if you devise an escape string function that doesn't affect the JSON's validity), you can do it by using the fnServerData function:
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": function (data) {
// run your escape string function to modify 'data'
fnCallback(data); // or fnCallback(newData) if you used new variable
}
});
}
If you're not sure about the safety of modifying it wholesale, you can do it on a row-by-row basis with the fnRowCallback:
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var cellData = myEscaper(aData[0]); // where myEscaper() is your own custom function
$('td:eq(0)').text(cellData);
return nRow;
}
In this sample, I'm only modifying the first cell. If it's applicable to all cells, you'll probably want to write an iterator that will go through the whole row to make the conversion. If it's only applicable to some cells, you can handle them one at a time.
Note that aData[0] and td:eq(0) only coincidentally have the same index (0). If you have any hidden columns, there will not necessarily be a match. Also, if you use mDataProp you will need to handle that as well.
Here are a couple of simple bits:
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
function htmlDecode(value) {
return $('<div/>').html(value).text();
}