我有一个奇怪的问题:
在数据库中,我有一个文字 & 符号和 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é's adventures of Tintin
contains the character entity reference for the e acute character).
这意味着当您键入(无效的 HTML)“标记开始”(<
)时,浏览器会将其更正为“小于号”(<
),但当您键入“实体开始”( &
), 是允许的,不会发生错误更正。
你需要写下你的意思。如果您想包含一些 HTML 作为数据,那么您必须将任何具有特殊含义的字符转换为其各自的字符引用。
如果数据是:
<div
那么 HTML 必须是:
<textarea>&lt;div</textarea>
您可以使用标准函数来转换它(例如 PHP 的 htmlspecialchars
或 Perl 的 HTML::Entities module )。
注意 1:如果您使用的是 XHTML[2](并且确实在使用它,如果您将其作为文本/html 提供则不算数),那么您可以使用显式 CDATA block :
<textarea><![CDATA[<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 < , 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/