是否有与 asp.net 中的 htmlencode / htmldecode 等效的 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3905310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a javascript equivalent of htmlencode / htmldecode from asp.net?
提问by NibblyPig
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 <and the same for >
停止脚本攻击很重要,asp.net 不会让你提交不安全的代码,所以提交你的 javascript 替换 <<和相同的 >
When the values are retrieved from the server, they will come back with <and >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.
数据应安全地存储在数据库中,因为其他人可能会使用此内容。从安全的角度来看,我想在它上面调用 htmlencode 然后存储它。我想在客户端的标签中显示这个编码的 html,但我想在文本框中显示解码的版本。
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?
所以我需要的是 javascript 中的 htmldecode 解决方案。htmlencode/decode 不仅仅是替换 < > 并且没有明确的列表我无法创建自己的方法。有解决办法吗?
回答by Quentin
Instead of trying to turn a string of text into HTML and then adding it to the document using innerHTML; use standard DOM methods.
而不是尝试将文本字符串转换为 HTML,然后使用 innerHTML 将其添加到文档中;使用标准的 DOM 方法。
myElement.appendChild(
document.createTextNode(myString)
);

