仅在Dom中将HTML解释为字符串

时间:2015-04-03 07:50:38

标签: javascript jquery html json dom

我正在尝试向我的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代码段看起来都不一样。

1 个答案:

答案 0 :(得分: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>