Javascript 从ajax检索时无法识别和显示HTML实体
这在所有经过测试的浏览器(Chrome、Firefox、Opera等)中都会发生 从ajax检索时,一些HTML实体被吞没而不显示。在HTML源文件中硬编码时,将显示相同的HTML实体Javascript 从ajax检索时无法识别和显示HTML实体,javascript,html,ajax,encoding,browser,Javascript,Html,Ajax,Encoding,Browser,这在所有经过测试的浏览器(Chrome、Firefox、Opera等)中都会发生 从ajax检索时,一些HTML实体被吞没而不显示。在HTML源文件中硬编码时,将显示相同的HTML实体 以下是实际输出:(实体不在网页或控制台中显示) 以下是预期输出: 以下是检索实体的javascript: <html><head><script type="text/javascript"> function injectEntity(){
以下是实际输出:(实体不在网页或控制台中显示)
以下是预期输出:
以下是检索实体的javascript: <html>
<head>
<script type="text/javascript">
function injectEntity(){
var xhr = new XMLHttpRequest();
xhr.open("POST", "entity.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
var doc = xhr.responseXML;
console.log(xhr.responseText);
var div = document.getElementById("container");
div.appendChild(doc.getElementById("the-entity"));
}
}
xhr.send(null);
}
</script>
</head>
<body>
<a href="#" onclick="injectEntity();">inject the following entity:</a> ’
<div id="container">
</div>
</body>
</html> <?php
header('Content-type: application/xml; charset=UTF-8');
$xml = new DOMDocument('1.0', 'utf-8');
$tag = $xml->createElement('b','’');
$tag->setAttribute("id","the-entity");
$xml->appendChild($tag);
echo $xml->saveXML();
?>
function injectEntity(){
var xhr=new XMLHttpRequest();
xhr.open(“POST”,“entity.php”,true);
var doc xhr.responseXML;
console.log(xhr.responseText)
var div=document.getElementById(“容器”);
div.appendChild(doc.getElementById(“实体”);
}
}
&146
下面是用于检索实体的php文件: <html>
<head>
<script type="text/javascript">
function injectEntity(){
var xhr = new XMLHttpRequest();
xhr.open("POST", "entity.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
var doc = xhr.responseXML;
console.log(xhr.responseText);
var div = document.getElementById("container");
div.appendChild(doc.getElementById("the-entity"));
}
}
xhr.send(null);
}
</script>
</head>
<body>
<a href="#" onclick="injectEntity();">inject the following entity:</a> ’
<div id="container">
</div>
</body>
</html> <?php
header('Content-type: application/xml; charset=UTF-8');
$xml = new DOMDocument('1.0', 'utf-8');
$tag = $xml->createElement('b','’');
$tag->setAttribute("id","the-entity");
$xml->appendChild($tag);
echo $xml->saveXML();
?>
你想要
’代码>,而不是代码>(这是一个无法打印的控制字符)谢谢。这是真的,但是为什么HTML实体;在HTML源页面中正确显示。我猜如果要替换实体,您必须解析文本。您可以使用innerHTML
解析文本。因此,不要使用appendNode
,而是使用innerHTML
将内容添加到DOM中。