2

我正在尝试使用 jQuery 来操作我用 ajax 加载的 XML 文件的 DOM。我可以选择元素、清空它们并删除它们,但不能添加它们。

jQuery 很少让我失望,但我感到筋疲力尽和失败了。请帮忙。

编码:

<script type="text/javascript">

$.ajax({
    type: "GET",
    url: "note.xml",
    dataType: "xml",
    success: parseResultsXML
});

function parseResultsXML(xml) {

    $(xml).append('<item>something</item>'); // Nothing gets added! :(
}

</script>
4

2 回答 2

3

I think you will need to use $.parseXML(xml) to parse the XML. parseXML() was new addition to jQuery 1.5. I had similar problem as you, and I ended up using some plugin library to parse XML because I was using jQuery 1.4.

http://api.jquery.com/jQuery.parseXML/

==== Edit ====

It's a bit tricky to manipulate XML using jQuery. Try the following code

var dom = $.parseXML(xml); //returns DOM element
var item = $.parseXML("<item>something</item>"); //returns DOM element

$(dom).children(0).append($(item).children(0))

console.log($(dom).find("item").text()); //should print "something"

You have to do $(dom).children(...) because dom is a document object, you have to wrap it into jQuery in order to use jQuery functions.

You have to do $(dom).children(0).append(...) but not $(dom).append() because dom refers to the document root of the XML DOM tree. recall all DOM looks like:

  Document
     |
    root
  /  |  \   
 c1  c2  c3 ....more children...

So if you do $(dom).append(..) you are actually trying to append to the document root which is not allowed because document root can only have one element child, namely the root element of your xml document.

Similarly, you do .append($(item).children(0)) because you want to insert the root element of item not the document root of item

于 2011-06-28T23:53:56.140 回答
-1

由于跨域 ajax问题,函数 parseResultsXML 永远不会被调用, http://www.w3schools.com/xml/note.xml与您的页面位于不同的域中。

而是将 xml 文件复制到您的站点,然后将代码更改为:

$.ajax({     
    type: "GET",     
    url: "/note.xml",     
    dataType: "xml",     
    success: parseResultsXML 
}); 
于 2011-06-28T22:47:31.133 回答