简体   繁体   English

如何在 thymeleaf 和 javascript 代码中转义单引号

[英]how to escape single quote in thymeleaf and javascript code

I need to update an html DOM using javascript, by inserting a link that will invoke a javascript function when a user clicks the link in a Thymeleaf template.我需要使用 javascript 更新 html DOM,方法是插入一个链接,当用户单击 Thymeleaf 模板中的链接时,该链接将调用 javascript 函数。

$.ajax({
  type: "GET",
  beforeSend: function(xhrObj){
    xhrObj.setRequestHeader("Content-Type","application/json");
    xhrObj.setRequestHeader("Accept","application/json");
  },
  url: "/users/list",
  dataType:"json",
  success: function( data,  textStatus,  jqXHR){
        var table = $("#userlist").children();
        for(i in data){
            table.append("<tr><td><a onclick='user_see("+data[i].userId+")' th:href='#'>"+data[i].userId+"</a></td><td>"+data[i].firstName+"</td><td>"+data[i].lastName+"
            }
   }
});

It turns out Thymeleaf replaces single quotes with double quotes.事实证明,Thymeleaf 用双引号替换了单引号。 I have tried escaping the singe quote with \\' but I only end up with a Thymeleaf parse error when the page is loaded我试过用 \\' 转义单引号,但我只在页面加载时出现 Thymeleaf 解析错误

Thu Oct 30 17:55:21 EAT 2014 There was an unexpected error (type=Internal Server Error, status=500). 2014 年 10 月 30 日星期四 17:55:21 发生意外错误(类型 = 内部服务器错误,状态 = 500)。 Exception parsing document: template="users/list",异常解析文档:template="users/list",

How can I escape the single quote?我怎样才能逃避单引号?

The safest thing would be not to append HTML as a string, but use the DOM API instead.最安全的做法不是将 HTML 作为字符串附加,而是使用 DOM API。 It's wordier, but avoids the quoting issues:它更冗长,但避免了引用问题:

 data.forEach(function(datum) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var a = document.createElement('a');
    a.onclick = function() { user_see(datum.userId); };
    a.setAttribute('th:href', '#');
    a.innerHTML = datum.userId;
    tr.appendChild(td);
    td = document.createElement('td');
    td.innerHTML = datum.firstName;
    tr.appendChild(td);
    td = document.createElement('td');
    td.innerHTML = datum.lastName;
    tr.appendChild(td);
    table.appendChild(tr);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM