简体   繁体   English

使用javascript编码/解码html

[英]encoding/decoding html using javascript

I am using Tinymce editor for formatting articles in my ASP.NET page. 我正在使用Tinymce编辑器来格式化ASP.NET页面中的文章。
here is my code:- 这是我的代码:-

 <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>

and this is what i have find on the web for encoding html here and tried to use it. 这就是我在网上找到的用于在此处编码html并尝试使用它的内容。

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);
}

and this also 这也

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

but it's not working for me and it doesn't even display htmlToEncode value in alert() function. 但它对我不起作用,甚至在alert()函数中也不显示htmlToEncode值。 Everytime I click submit button, it display the following error 每次单击提交按钮时,都会显示以下错误

A potentially dangerous Request.Form value was detected from the client and etc.. 从客户端等检测到潜在危险的Request.Form值。

Please help to figure out the Problem. 请帮助找出问题所在。 I want to encode the HTML content and then store it into the database and then to retrieve it on another page. 我想对HTML内容进行编码,然后将其存储到数据库中,然后在另一页上进行检索。

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;

TinyMCE editor already encode tags written by user. TinyMCE编辑器已经对用户编写的标签进行了编码。

To decode those tags, you can use the following line 要解码这些标签,您可以使用以下行

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

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

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