Is it possible to add,delete xml nodes with jquery $.ajax?

强颜欢笑 提交于 2019-12-03 21:35:04

jQuery is a fantastic tool for parsing and manipulating XML in javascript. jQuery's ajax APIs were, in fact, built with this in mind which is why you're able to specify the response type of an ajax call by setting the dataType argument to xml (although they do try to do some auto-detection if this argument is omitted). From the jQuery $.ajax() documentation for the dataType argument:

"xml": Returns a XML document that can be processed via jQuery.

You can parse and manipulate XML as much as want using jQuery. I'll have to add that using CSS selectors is wonderful compared to XPath queries in server-side XML libraries.

While empty and remove work as expected, there's a gotcha when adding nodes on the fly with functions like append: jQuery, for whatever reason (I haven't really dug into this), won't create the element for you when appending to the XML structure (although this works fine in HTML structures). You can get around this easily by explicitly creating the node yourself as a DOM element or jQuery object and then calling append:

//Either of these will work
var elem = document.createElement('app');
xml.find('layout').append(elem); // Appends <app></app> to <layout>
xml.find('layout').append($('<app>')); // Does the same

// You can also you use other manipulation functions such as `attr`
xml.find('layout').append($('<app>').attr('id', 'ego'));

It looks like, however, that there are other problems with your code that would be preventing it from behaving as expected. The $.ajax beforeSend callback, for example, passes in the XMLHttpRequest object to the callback function and not your XML object to be manipulated. The result is that your empty call in that callback does nothing.

Also, if you're trying to manipulate the response of Database/UserConfig/config.xml in the beforeSend callback, it probably won't have existed yet since beforeSend is called before the ajax request is fired off. It's possible that the xml argument you intended to pass in was scoped globally, but it's squashed in the scope of the callback since jQuery is passing in XMLHttpRequest as I mentioned before.

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