1

Okay, I'm pulling data from an XML file to populate my elements of my webpage dynamically. My problem is that when I use JQuery .ajax to pull the xml file, it strips my HTML tags.

For example,

Data in XML file:

<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:

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

I've tried to use JQuery's '.html()' but it returns null. What is the simplest way I can fix this? Preferably without changing too much of what I've already done.

Thanks in advance.

4

1 回答 1

6

Using text will strip the tags as you experienced. You can instead use the jQuery children method (reference) on the transcript node to get the HTML. Here is a working example: 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.

Issues

When taking HTML from an XML response it may be missing the default styles. For example, a paragraph tag may not have 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.

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.

于 2012-12-03T18:53:21.910 回答