简体   繁体   English

JQuery 的 ajax 函数从 XML 中剥离 HTML 标签

[英]JQuery's ajax function stripping HTML tags from XML

Okay, I'm pulling data from an XML file to populate my elements of my webpage dynamically.好的,我正在从 XML 文件中提取数据以动态填充我的网页元素。 My problem is that when I use JQuery .ajax to pull the xml file, it strips my HTML tags.我的问题是,当我使用 JQuery .ajax 来提取 xml 文件时,它会去除我的 HTML 标签。

For example,例如,

Data in XML file: XML 文件中的数据:

<transcript><p>Hello, world</p></transcript>

Desired output on webpage:网页上所需的输出:

<p>Hello, world</p>

Actual output:实际输出:

Hello World

Here is my code inside of my ajax function:这是我的 ajax 函数中的代码:

$(xmlData).find('item').each(function() {
        var n = $(this).find('transcript').text();

I've tried to use JQuery's '.html()' but it returns null.我尝试使用 JQuery 的 '.html()' 但它返回 null。 What is the simplest way I can fix this?我可以解决这个问题的最简单方法是什么? Preferably without changing too much of what I've already done.最好不要改变太多我已经做过的事情。

Thanks in advance.提前致谢。

Using text will strip the tags as you experienced.使用text将根据您的经验剥离标签。 You can instead use the jQuery children method ( reference ) on the transcript node to get the HTML.您可以改为使用转录节点上的 jQuery children方法(参考)来获取 HTML。 Here is a working example: http://jsfiddle.net/gjwyd/这是一个工作示例: http : //jsfiddle.net/gjwyd/

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "/echo/xml/",
        dataType: "xml",
        data: {
            xml: "<transcript><p>Hello, world</p></transcript>"
        },
        success: function(xml) {
            var container = $('#content');
            var html = $(xml).find('transcript').children();
            container.html(html);
        }
    });
});​

The key is this line:关键是这一行:

var html = $(xml).find('transcript').children();

And being sure to set the dateType as xml.并确保将 dateType 设置为 xml。

Issues问题

When taking HTML from an XML response it may be missing the default styles.从 XML 响应中获取 HTML 时,它可能缺少默认样式。 For example, a paragraph tag may not have display: block .例如,段落标签可能没有display: block Resetting the styles may be one way around this issue.重置样式可能是解决此问题的一种方法。 A more correct and probably easier way would be to put the HTML content inside of CDATA within the XML as one of the other commenters suggested.一种更正确且可能更简单的方法是将 HTML 内容放在 XML 中的 CDATA 内,正如其他评论者之一所建议的那样。

http://jsfiddle.net/tZJQp/ http://jsfiddle.net/tZJQp/

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "/echo/xml/",
        dataType: "xml",
        data: {
            xml: "<transcript><![CDATA[<p>Hello, world</p><p>Bye</p>]]></transcript>"
        },
        success: function(xml) {
            var container = $('#content');
            var html = $(xml).find('transcript').text();
            container.html(html);
        }
    });
});

As others note, html won't work on XML.正如其他人所指出的, html不适用于 XML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM