How do I get the entire XML string from a XMLDocument returned by jQuery (cross browser)?

旧巷老猫 提交于 2019-11-27 21:01:05

I need the actual XML as a string

You want it as plain text instead of XML object? Change dataType from 'xml' to 'text'. See the $.ajax documentation for more options.

If you want both, get the response as XML Document and as string. You should be able to do

success: function(data){
  //data.xml check for IE
  var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
  alert(xmlstr);
}

If you want it as string why do you specify dataType:xml wouldn't then dataType:text be more appropriate?

You can also easily convert an xml object to a string, in your java script:

var xmlString = (new XMLSerializer()).serializeToString(xml);

If you only need a string representing the xml returned from jquery, just set your datatype to "text" rather than trying to parse the xml back into text. The following should just give you raw text back from your ajax call:

$.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'text',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});

Although this question has already been answered, I wanted to point out a caveat: When retrieving XML using jQuery with Internet Explorer, you MUST specify content-type to be "text/xml" (or "application/xml") or else you will not be able to parse the data as if it were XML using jQuery.

You may be thinking that this is an obvious thing but it caught me when using Mozilla/Chrome/Opera instead of IE. When retrieving a "string" of XML with a content-type of "text", all browsers except IE will still allow you to parse that data (using jQuery selectors) as if it were XML. IE will not throw an error and will simply not return any results to a jQuery selection statement.

So, in your example, as long as you only need the string-serialized version of the XML and will not expect jQuery to do any sort of selection on the XML DOM, you can set the content-type to "text". But if you ALSO need to parse the XML with jQuery, you will need to write a custom routine that serializes the XML into a string for you, or else retrieve a version of the XML with content-type "xml".

Hope that helps someone :)

You can get the native XMLHttpRequest object used in the request. At the time i'm posting this answer, jQuery docs state a few ways to do so.

One of them is via the third argument of the success callback:

success: function(xml, status, xhr){
    console.log(arguments);
    console.log(xhr.responseXML, xhr.responseText);
    console.log('Finished!');
}

For a complete example: https://jsfiddle.net/44m09r2z/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!