问题描述
我想我有一个非常简单的问题,但我找不到解决方案。
所以我想要的是通过HTML加载DIV内容。问题是它不仅仅是一个文本,还有一个图像。 ajax调用返回HTML代码,但它在DIV中显示为HTML并且不会执行。难以解释,但从示例中显而易见...
AJAX调用返回字符串:
I think I have a very simple question, but I couldn't find a solution.So what I want is to load a DIV content via HTML. The problem is that it is not just a text, but also an image. The ajax call returns the HTML code, but this is displayed in the DIV as HTML and is not executed. Difficult to explain, but obvious from the example...The AJAX call returns the string:
<img src="/images/weather/1.png" width="80px"><br>3.3 °C
问题很明显。而不是图像和div中的3.3°C,我得到的是实际代码,所以代替图像我看到img src = ....
The problem is obvious. Instead of an image and the 3.3°C in the div, I get the actual code, so instead of the image I see img src=....
我知道我需要以某种方式解码HTML,但我不知道如何做到这一点,非常感谢任何帮助。
I know that i need to somehow decode the HTML, but I have no clue how to do this and would very much appreciate any help.
我的Javascript代码是:
My Javascript code is:
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
newtext = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "message_ajax.php", true);
xmlhttp.send();
$('#text').fadeOut(function () {
$(this).text(newtext).fadeIn();
})
推荐答案
你应该使用 $(this).html(newtext)
而不是 $(this).text(newtext)
。
他们完全不同。 将逃脱 您的HTML并将其插入为简单的文本。或者正如文档所述:
They are quite different. .text()
will "escape" your HTML and insert it as simply text. Or as the documentation states:
你应该首先阅读文档。
如果你已经在使用jQuery,你可以使用它的,让您的生活更轻松。
If you are already using jQuery, you could use it's AJAX methods which make your life much easier.
这篇关于通过ajax将DIV内容加载为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!