40

我已经尝试并未能找出如何从 GET 返回的 XMLDocument 中获取整个 XML 字符串。关于如何在对象中查找或替换特定元素的问题有很多,但我似乎找不到如何将整个文档作为字符串获取的任何答案。

我正在使用的示例来自这里。“用 xm​​l 做某事”部分是我目前所处的位置。我觉得这应该是微不足道的,但我不知道怎么做。是否有可用于此目的的“xml.data()”或类似的?

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

用例是我想将 xml 提供给 flash 插件,为此我需要实际的 XML 作为字符串。

4

6 回答 6

54

如果两者都需要,请以 XML 文档和字符串的形式获取响应。你应该能够做到

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

如果你想要它作为字符串,为什么你指定dataType:xml不会dataType:text更合适?

于 2009-11-04T16:39:00.033 回答
44

我需要实际的 XML 作为字符串

您希望它是纯文本而不是 XML 对象吗?dataType从更改'xml''text'。有关更多选项,请参阅$.ajax 文档

于 2009-11-04T16:38:10.800 回答
23

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

var xmlString = (new XMLSerializer()).serializeToString(xml);
于 2012-05-24T13:37:53.837 回答
1

如果您只需要一个表示从 jquery 返回的 xml 的字符串,只需将您的数据类型设置为“文本”,而不是尝试将 xml 解析回文本。以下内容应该只是从您的 ajax 调用中返回原始文本:

$.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'text',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});
于 2009-11-04T16:39:55.240 回答
1

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

于 2011-07-13T15:53:08.653 回答
1

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/

于 2016-03-01T17:27:25.490 回答