Is there a javascript equivalent of htmlencode / htmldecode from asp.net?

风流意气都作罢 提交于 2019-12-10 17:13:51

问题


The problem is this:

You have a textbox, you type in some text, send it to the server. On another page, that value is retrieved and displayed on screen in a textbox and a label.

It's important to stop scripting attacks, and asp.net won't let you submit unsafe code, so on submit you javascript replace < with &lt; and the same for >

When the values are retrieved from the server, they will come back with &lt; and &gt; which is fine for displaying in the label, but when put into the textbox, they must be replaced back to < and >

The data should be stored securely in the database as other people might use this content. From a safety point of view I'd like to call htmlencode on it then store it. It is this encoded html I'd like to display in the label on the client, but the decoded version I'd like to display in the textbox.

So what I need, is a htmldecode solution in javascript. htmlencode/decode replaces more than just < > and without a definitive list I can't create my own method. Is there a solution out there?


回答1:


Instead of trying to turn a string of text into HTML and then adding it to the document using innerHTML; use standard DOM methods.

myElement.appendChild(
    document.createTextNode(myString)
);


来源:https://stackoverflow.com/questions/3905310/is-there-a-javascript-equivalent-of-htmlencode-htmldecode-from-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!