小于 (<) 符号在 jQuery 数据表中是不允许的



有小需求,我想用JSON数据显示数据表,这里我有一个小挑战,如果JSON数据有像lessthan symbol(<)这样的特殊字符,数据就不会显示在数据网格中。不知道为什么只有lessthan symbol(<)出现问题我尝试了以下代码,如果有遗漏,请纠正我,例如:姓Jhons<asdf,但只显示Jhons请帮我一下。

这是我的样本代码

$.ajax({
    url: '/echo/json/',
    type: "post",
    dataType: "json",
    data: {
        json: JSON.stringify([
            {
            id: 1,
            firstName: "Peter&heins",
            lastName: "Jhons<asdf"},
        {
            id: 2,
            firstName: "David>tyy",
            lastName: "Bowie<wwww"},
            {
            id: 2,
            firstName: "David<test",
            lastName: "testqwwe>qewrqwe"}
        ]),
        delay: 3
    },
    success: function(data, textStatus, jqXHR) {
        // since we are using jQuery, you don't need to parse response
        drawTable(data);
    }
});
function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}
function drawRow(rowData) {
    var row = $("<tr />")
    $("#personDataTable").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
    row.append($("<td>" + rowData.id + "</td>"));
    row.append($("<td>" + rowData.firstName + "</td>"));
    row.append($("<td>" + rowData.lastName + "</td>"));
}

JSFiddle

感谢

演示

你可以使用

row.append($("<td>" + rowData.lastName.replace("<","&lt") + "</td>"));

代替

row.append($("<td>" + rowData.lastName + "</td>"));

如果在文本中使用小于(<)或大于(>)符号,浏览器可能会将它们与标记混合使用。字符实体用于在HTML中显示保留字符。

手动

由于<是HTML中的一个特殊字符,您需要对其进行转义。

row.append($("<td>").text(rowData.firstName));

最新更新