40

GET によって返された XMLDocument から XML 文字列全体を取得する方法を見つけようとしましたが、失敗しました。オブジェクト内の特定の要素を検索または置換する方法については、SO に関する多くの質問がありますが、ドキュメント全体を文字列として取得する方法に対する答えが見つからないようです。

私が取り組んでいる例はhereからです。「xmlで何かをする」部分は、私が今いるところです。これは本当に些細なことだと思いますが、その方法がわかりません。この目的に使用できる「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

44

実際の XML が文字列として必要です

XML オブジェクトではなく、プレーン テキストとして使用しますか? dataTypeから'xml'に変更し'text'ます。その他のオプションについては、 $.ajax のドキュメントを参照してください。

于 2009-11-04T16:38:10.800 に答える
23

また、Javaスクリプトでxmlオブジェクトを文字列に簡単に変換することもできます。

var xmlString = (new XMLSerializer()).serializeToString(xml);
于 2012-05-24T13:37:53.837 に答える
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

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 に答える