且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以使用jquery $ .ajax添加,删除xml节点?

更新时间:2022-06-01 23:13:08

jQuery是一个出色的工具,用于解析和处理XML。 javascript。 jQuery的ajax API实际上是在考虑这一点的基础上构建的,这就是为什么您可以通过将 dataType 参数设置为 xml (尽管如果忽略此参数,它们也会尝试进行一些自动检测)。从jQuery $。ajax()文档获取 dataType 参数:

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:返回可以通过jQuery处理
的XML文档。

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

您可以使用jQuery任意解析和处理XML。我必须补充一点,与服务器端XML库中的XPath查询相比,使用CSS选择器是很棒的选择。

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.

为空删除时,按预期工作,使用诸如$code> append 之类的函数动态添加节点时的陷阱:jQuery,无论出于何种原因(我没有真正研究过),都不会为您创建元素追加到XML结构时(尽管在HTML结构中效果很好)。通过自己将节点显式创建为DOM元素或jQuery对象,然后调用 append

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'));

但是,看起来您的代码还有其他问题会阻止它的行为如预期的那样。例如, $。ajax beforeSend 回调传递 XMLHttpRequest 指向回调函数的对象,而不是要处理的XML对象。结果是您在该回调中的 empty 调用没有任何作用。

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.

此外,如果您要操作在 beforeSend 回调中 Database / UserConfig / config.xml 的响应,自从它可能还不存在在触发ajax请求之前调用 beforeSend 。您打算传递的 xml 参数可能是全局范围的,但是由于jQuery传递了 XMLHttpRequest 正如我之前提到的。

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.