【问题标题】:injected HTML Interprets as string only in Dom注入的 HTML 仅在 Dom 中解释为字符串
【发布时间】:2015-06-08 07:34:20
【问题描述】:

我正在尝试像这样向我的 Dom 注入 HTML

   var oldhtmlString = // Getting html from an ajax query
  $this.parent('td').find('.newhtml').html ( oldhtmlString);

从数据库生成 HTML 的服务器端代码

DataSet ds = DataAccessLayer.Instance.ExecuteThisSQLAndGetDataSet("select * from UpdateEmail");
        var table = ds.Tables[0].DefaultView.ToTable();  
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(table);

我从 JSON 元素内的外部源获取 HTML 字符串,并尝试将其注入到我的 Dom 内的元素中。但它仅作为字符串注入,如下所示

        <div class="newhtml">
&lt;div style="font-size: 11px; font-family: Verdana;"&gt;&lt;p&gt;Please note that the values f::1&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;p&gt;This is an automated message. Please DO NOT reply and contact the Warehouse directly for further questions.&lt;/div&gt;
 </div>

原始 HTML 取自数据库。看起来像这样

<div style="font-size: 11px; font-family: Verdana;"><p>Please note that the values for CO #  509226, This is an automated message. Please DO NOT reply and contact the Warehouse directly for further questions.</p></div>

当它通过 JSON 对象中的 ajax 到达客户端时,它看起来像这样

LogHTML: "<div style="font-size: 11px; font-family: Verdana;"><p>Please note that the values for ::1</td></tr></table><p>This is an automated message. Please DO NOT reply and contact the Warehouse directly for further questions.</p></div>"

谁能告诉我如何在我的 Dom 中正确显示这个 HTML?

注意:只有 HTML 数据格式是正确的。由于隐私原因,我更改了该 HTML 中的数据,因此上述每个 HTML 代码 sn-ps 看起来都没有什么不同。

【问题讨论】:

  • 原来的 HTML 源代码似乎被转义了。您正在使用 html 方法,它不会转义传递的 HTML 字符串。
  • @Vohuman 我不完全理解,您能否将其添加为带有正确代码和解释的答案
  • 显示 oldhtmlString 的样子,你的 Ajax 查询的样子。另外,你写的是服务器端代码吗?
  • @Tomalak 我现在已经添加了详细信息。请检查

标签: javascript jquery html json dom


【解决方案1】:

试试这个:

        
var oldhtmlString = '&lt;div style="font-size: 11px; font-family: Verdana;"&gt;&lt;p&gt;Please note that the values f::1&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;p&gt;This is an automated message. Please DO NOT reply and contact the Warehouse directly for further questions.&lt;/div&gt;'

$('.newhtml').html( $('<div/>').html(oldhtmlString).text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="newhtml"> </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-04
    • 2015-01-28
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多