html - 如何阻止 html TEXTAREA 解码 html 实体

标签 html decoding html-entities

我有一个奇怪的问题:

在数据库中,我有一个文字 & 符号和 lt 分号:

<div  

每当它被打印到 html textarea 标签中时,页面的源代码将 > 显示为 >

如何停止解码?

最佳答案

您无法阻止实体在文本区域中被解码,因为文本区域的内容不是(不像脚本或样式元素)固有的 CDATA,即使错误恢复可能有时 给人这样的印象。

textarea元素的定义是:

<!ELEMENT TEXTAREA - - (#PCDATA)       -- multi-line text field -->

即它包含 PCDATA is described as :

Document text (indicated by the SGML construct "#PCDATA"). Text may contain character references. Recall that these begin with & and end with a semicolon (e.g., Herg&eacute;'s adventures of Tintin contains the character entity reference for the e acute character).

这意味着当您键入(无效的 HTML)“标记开始”(<)时,浏览器会将其更正为“小于号”(&lt;),但当您键入“实体开始”( & ), 是允许的,不会发生错误更正。

你需要写下你的意思。如果您想包含一些 HTML 作为数据,那么您必须将任何具有特殊含义的字符转换为其各自的字符引用。

如果数据是:

&lt;div

那么 HTML 必须是:

<textarea>&amp;lt;div</textarea>

您可以使用标准函数来转换它(例如 PHP 的 htmlspecialchars 或 Perl 的 HTML::Entities module )。

注意 1:如果您使用的是 XHTML[2](并且确实在使用它,如果您将其作为文本/html 提供则不算数),那么您可以使用显式 CDATA block :

<textarea><![CDATA[&lt;div]]></textarea>

注意 2:或者如果浏览器正确实现了 HTML 4


Ok , but the question is . why it decodes them anyway ? assuming i've added & , save the textarea , ti will be saved &lt; , but displayed as < , saving it again will convert it back to < (but it will remain < in the database) , saving again will save it a < in the database , why the textarea decodes it ?

  • 服务器发送(到浏览器)编码为HTML的数据。
  • 浏览器发送(到服务器)编码为application/x-www-form-urlencoded(或multipart/form-data)的数据。

由于浏览器不以 HTML 格式发送数据,因此字符不表示为 HTML 实体。

如果您将从客户端接收到的数据,然后将其放入 HTML 文档中,那么您必须先将其编码为 HTML。

关于html - 如何阻止 html TEXTAREA 解码 html 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8519070/

相关文章:

jquery - 如何使用jquery方法post发送tinymce内容

json - 如何在 Swift 中解码 HTML 实体?

html - 为什么:first-child selector not working in this case?

javascript - 在中小屏幕设备上隐藏侧边栏

java - 解码密码或一些更复杂的方式来为用户发送密码?

sql - 从数据库中删除 html 实体

javascript - 为什么这个函数 getElementsByClassName 不能在 IE7,8 上运行?

javascript - 带有url的页面加载的过渡效果

vb.net - 如果不是 Base64,可能是什么?

algorithm - 解析 GIF 栅格数据 - LZW