[英]How to make browser NOT parse new HTML code that added from javascript
I want to add some text to my webpage from my server with ajax, but the text includes some html tags, and browsers tend to parse that code and render it. 我想使用ajax从服务器向网页中添加一些文本,但是该文本包含一些html标签,浏览器倾向于解析该代码并将其呈现。 I don't want this behavior, i want to appent that text without parsing the html tags. 我不想这种行为,我想在不解析html标签的情况下显示该文本。 Is there way to accomplish this? 有办法做到这一点吗?
you have to encode the returned "HTML". 您必须对返回的“ HTML”进行编码 。 basically you have to replave <
, >
and &
with <
基本上,您必须用<
替换<
, >
和&
<
, >
, >
and &
和&
. 。
if you're using PHP on serverside, for example, you could do this using htmlspecialchars()
- there might be similar functions or methods available for other languages ( cgi.escape for python, HTML:Entities for Perl, System.Web.HttpUtility.HtmlEncode for asp.net ...). 例如,如果您在服务器端使用PHP,则可以使用htmlspecialchars()
-其他语言可能有类似的功能或方法(python的cgi.escape ,Perl的HTML:Entities , System.Web.HttpUtility .HtmlEncode for asp.net ...)。
if you do this on a retuned string that looks like 如果您对看起来像这样的经过重新调整的字符串执行此操作
this is <strong>bold</strong> text
wich is shown in your browser as 夹在您的浏览器中显示为
this is bold text 这是粗体字
your output will change to 您的输出将更改为
this is <strong>bold</strong> text
wich will display as wich将显示为
this is <strong>bold</strong> text 这是<strong>粗体</ strong>文字
Use node.textContent
property (element.innerText on IE<=8) to assign textual content to an element. 使用node.textContent
属性(IE <= 8上的element.innerText)将文本内容分配给元素。 Browser will encode all special characters into the respective HTML entities: 浏览器会将所有特殊字符编码为各自的HTML实体:
var h1 = document.getElementsByTagName("h1")[0];
if (typeof h1.textContent != "undefined") {
h1.textContent = "<b>Hello World</b>";
}
else if (typeof h1.innerText != "undefined") {
h1.innerText = "<b>Hello World</b>";
}
alert(h1.innerHTML);
// at this point, the h1 tag will "render" <b>Hello World</b>
// not the text Hello World in bold face
// inspecting the element will reveal that html tags, e.g. <b>
// were converted to <b>
In browser-side javascript: 在浏览器端的javascript中:
function htmlEncode( str ) {
str = str + "";
var el = document.createElement("div");
el.appendChild( document.createTextNode( str ) );
return el.innerHTML;
}
htmlEncode( "<div></div>" );
//"<div></div>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.