通过ajax将DIV内容加载为HTML [英] Loading DIV content via ajax as HTML

查看:875
本文介绍了通过ajax将DIV内容加载为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我有一个非常简单的问题,但我找不到解决方案。
所以我想要的是通过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)

他们完全不同。 .text() 将逃脱 您的HTML并将其插入为简单的文本。或者正如文档所述:

They are quite different. .text() will "escape" your HTML and insert it as simply text. Or as the documentation states:


我们需要知道这个方法会转义为
提供的字符串,这样它就会在HTML中正确呈现。为此,它调用
DOM方法.createTextNode(),不会将字符串解释为
HTML。

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.

你应该首先阅读文档。

如果你已经在使用jQuery,你可以使用它的 AJAX方法,让您的生活更轻松。

If you are already using jQuery, you could use it's AJAX methods which make your life much easier.

这篇关于通过ajax将DIV内容加载为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆