使用javascript编码/解码html

时间:2013-07-12 07:35:35

标签: javascript html asp.net encoding

我正在使用Tinymce编辑器格式化我的ASP.NET页面中的文章 这是我的代码: -

 <asp:TextBox runat="server" ID="textarea" Height="70px" 
        Width="324px" TextMode="MultiLine"></asp:TextBox><br />
    <asp:Button ID="submit" runat="server" Text="Button" 
    OnClientClick="encodeMyHtml()" onclick="submit_Click" CausesValidation="False"/>
</div>

这就是我在网上找到的用于编码html here并尝试使用它的内容。

function encodeMyHtml() {
    var htmlToEncode = document.getElementById("textarea").value;
    // save content after encoding
    alert(htmlToEncode);
    var encodedHtml = escape(htmlToEncode);
    alert(encodedHtml);
    // Later when displaying it back, decode it.
    var ohtml = unescape(encodedHtml);
    alert(ohtml);
}

这也是

   function encodeMyHtml() {
      var htmlText = document.getElementById('textarea').value;
      htmlText = htmlText.replace(/\</g, "&lt;");
      //alert("hello2");
      htmlText = htmlText.replace(/\>/g, "&gt;");
      alert(htmlText);
 }

但它对我不起作用,它甚至不在alert()函数中显示htmlToEncode值。每次我点击提交按钮,它都会显示以下错误

  

从客户端等检测到潜在危险的Request.Form值。

请帮助解决问题。我想对HTML内容进行编码,然后将其存储到数据库中,然后在另一个页面上检索它。

2 个答案:

答案 0 :(得分:0)

var text = document.getElementById("myTextarea").value;

// temporary element has all the native encoding capability you need
var p = document.createElement('p');

// set text and get back HTML
p.appendChild( document.createTextNode(text) );
var html = p.innerHTML;

// add line breaks to display in elements that don't preformat (like textarea does)
html = html.replace(/(\r\n|\n|\r)/g, '<br />' );

// set html and get back text
p.innerHTML = html;
text = p.textContent||p.innerText;

答案 1 :(得分:0)

TinyMCE编辑器已对用户编写的标签进行编码。

要解码这些标记,您可以使用以下行

    var decodedHtml = $('<div/>').html(yourText).text();
相关问题