在 Ajax 的 jQuery 示例页面上看到了这个示例:
var xmlDocument = [create xml document];
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,
success: someFunction
});
我如何获取像这样的字符串:
var t = '<foo><bar>something</bar></foo>';
然后将其转换为 XML DOM 对象?跨浏览器?
更新: 请参阅对 karim79 的回答的评论。
最佳答案
将它包装在一个 jQuery 对象中。然后在其上使用 jQuery 的常规 DOM 操作方法。
var t = $('<foo><bar>something</bar></foo>');
//loop over 'bar' nodes
t.find('bar').each(function () {
alert($(this).text());
});
如果你想将它转换回一个纯字符串(例如在修改它之后)你可以这样做:
//then convert it back to a string
//for IE
if (window.ActiveXObject) {
var str = t.xml;
alert(str);
}
// code for Mozilla, Firefox, Opera, etc.
else {
var str = (new XMLSerializer()).serializeToString(t);
alert(str);
}
编辑:$.ajax manual says (在 processData 选项上):
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, or other non-processed data, set this option to false.
因此,如果您要将 jQuery 对象传递给服务器,则需要将其设置为 true,或者完全忽略它(它设置为 true默认)。希望有所帮助。
关于javascript - 在 JavaScript 中将字符串转换为 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1290321/