开发者

Escape markup in JSON-driven jQuery datatable?

开发者 https://www.devze.com 2023-04-12 17:38 出处:网络
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 potent开发者_开发技巧ial mark

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 potent开发者_开发技巧ial 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.


[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 completely.]

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消