JSON驱动的jQuery datatable中的转义标记? [英] Escape markup in JSON-driven jQuery datatable?

查看:379
本文介绍了JSON驱动的jQuery datatable中的转义标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jquery datatable ,它使用 sAjaxSource 财产。一切都很好,除了加载的内容被视为潜在的标记,所以如果单元格中的文本包含 或somesuch,那么事情会变得奇怪。

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.

推荐答案

p> [注意:以下答案是针对数据表1.9x及更低版本。 1.10改变了方法命名约定和其他一些事情。 1.9x方法可用但不推荐使用,不可避免地完全被完全剥离。]

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

如果可以剥离他们批发(即,如果你设计一个转义字符串函数这不影响JSON的有效性),您可以使用fnServerData函数来执行:

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

如果您不确定修改批发的安全性,可以使用fnRowCallback逐行执行:

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.

请注意,aData [0]和td:eq(0)只是巧合地具有相同的索引(0)。如果您有任何隐藏的列,则不一定会有匹配。另外,如果你使用mDataProp,你也需要处理这个。

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.

这篇关于JSON驱动的jQuery datatable中的转义标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆