简体   繁体   中英

Simulating jQuery $.post / $.ajax for XML reading

Possibly odd question; I'm trying to load an XML into jQuery to traverse it.

Using $.post I can do this perfectly, and specify XML as the dataType. My question revolves around how I can get jQuery to use that dataType to understand the same data if it is already in the page, ie I have it in a variable.

Whenever I use exactly the same XML data in a variable it can't traverse it properly.

I've tried taking out the declaration and removing question marks, escaping quotes etc.

I've tried loading like:-

var xml = new XML('<blah><moo>134</moo></blah>');

and of course

var xml = $('<blah><moo>134</moo></blah>');

and

var xml = '<blah><moo>134</moo></blah>';

and

var xml = "<blah><moo>134</moo></blah>";

etc. What am I doing wrong?

The problem is that jQuery doesn't parse XML, except using the built-in browser responseXML property of XMLHttpRequest when doing Ajax requests. If you pass an XML string to $() , it simply assumes it's HTML, assigns it as the innerHTML of an HTML element and reads the children of that HTML element. This is not XML parsing.

To parse XML, you can use a function like the following:

var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xml = parseXml("<blah><moo>134</moo></blah>");
if (xml) {
    window.alert(xml.documentElement.nodeName);
}

UPDATE

jQuery 1.5's new parseXML() method does exactly this, and seems to work well.

var xml = $.parseXML("<blah><moo>134</moo></blah>");

This gives you an XML document, which you can then traverse using jQuery in the usual way:

var $xml = $(xml);
alert($xml.find("moo:first")[0].nodeName);

Here is a sample that uses $.ajax and works cross browser (well Chrome, IE8, FireFox 3.6):

var pathToXML = "http://www.site.com/data/data.xml";
var xml;
    $.ajax({type: "GET", 
            url: pathToXML,
            cache: false, 
            dataType: ($.browser.msie) ? "text" : "xml",
            error: function(XMLHttpRequest, textStatus, errorThrown){alert(textStatus)},
            success: function(data){
            // workaround for msie
            if (typeof data == "string") {
                    xml = new ActiveXObject("Microsoft.XMLDOM");
                    xml.async = false; xml.loadXML(data);
            } else { xml = data; }
            xml.setProperty("SelectionLanguage", "XPath");
            // end workaround
            // use $(xml).find('node').text();
            var bobsNodeValue = $(xml).find("node[id='bob']").text();
    }});

This also sets it up as actual XML, which jQuery can traverse like a normal DOM tree using .find() and .text() .

EDIT:: Just read through the new comments to the question. Can you post an example of the failed xml here? Also, using .html() will probably result in errors whereas .text() should return a blank string for empty nodes.

EDIT EDIT:: Here is a fiddle showing no errors, what code are you using to traverse and is it all browsers or just a particular one?

您尝试在将xml发送到jQuery之前对其进行urlencode?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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