Simulate jQuery $ .post / $. Ajax to read XML

Perhaps a strange question; I am trying to load XML in jQuery to cross it.

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

Whenever I use exactly the same XML data in a variable, it cannot normally move it.

I tried to take out the ad and remove the question marks, avoid quotes, etc.

I tried downloading, for example: -

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?

+3
source share
3 answers

, jQuery XML, responseXML XMLHttpRequest Ajax. XML- $(), HTML, innerHTML HTML HTML. XML.

XML :

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 parseXML() , , .

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

XML-, jQuery :

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

, $.ajax - ( 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();
    }});

XML, jQuery , DOM, .find() .text().

EDIT:: . xml? , .html(), , , .text() .

EDIT EDIT:: fiddle, , , ?

+2

Have you tried urlencode xml before submitting it to jQuery?

0
source

Source: https://habr.com/ru/post/1788007/


All Articles