Escape markup in JSON-driven jQuery datatable?

I am using jquery datatable which dynamically loads JSON using the sAjaxSource property. Everything is fine, except that the downloaded content is considered as potential markup, so everything is strange if the text in the cells contains < or somesuch.

How can I get datatables to avoid my data before loading them into a table? I do not want to do this on the server side, because the server does not care what the client will do with the data.

+8
javascript jquery datatables
source share
2 answers

[note: the following answer is for DataTables 1.9x and below. 1.10 changed method naming conventions and a few other things. 1.9x methods are available but outdated and will inevitably be removed completely.]

If it’s safe to strip them of β€œwholesale” (that is, if you create an escape line function that does not affect JSON fairness), you can do this 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 are not sure about the safety of changing his wholesale business, you can do this in turn, line by line, using 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 example, I only change the first cell. If this applies to all cells, you probably want to write an iterator that will go through the entire line to do the conversion. If this applies only to some cells, you can process them one at a time.

Note that aData [0] and td: eq (0) only match the same index (0). If you have hidden columns, there will not necessarily be a match. Also, if you are using mDataProp, you will also need to handle this.

+3
source share

Here are a few simple bits:

 function htmlEncode(value) { return $('<div/>').text(value).html(); } function htmlDecode(value) { return $('<div/>').html(value).text(); } 
+2
source share

All Articles