在JavaScript中将字符串转换为XML文档 [英] Convert String to XML Document in JavaScript
问题描述
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> /栏>< /富>');
//循环'bar'节点
t.find('bar')。each(function(){
alert($(this).text()) ;
});
如果要将其转换为纯字符串(例如修改后),您可以它像这样:
//然后将其转换回字符串
// for IE
if (window.ActiveXObject){
var str = t.xml;
alert(str);
}
// Mozilla,Firefox,Opera等的代码
else {
var str =(new XMLSerializer())。serializeToString(t);
alert(str);
}
编辑: $。ajax manual说(在processData选项上):
默认情况下,传入数据
选项作为对象的数据(技术上,
除了字符串之外的任何东西)将被
处理并转换为查询
字符串,适合默认
content-type
application / x-www-form-urlencoded。
如果要发送DOMDocuments或
其他未处理的数据,请将此
选项设置为false。
所以如果你将jQuery对象传递给服务器,你需要将它设置为 true ,或者完全省略(它设置为 true 强>默认)。希望有所帮助。
Saw this example on the jQuery examples page for Ajax:
var xmlDocument = [create xml document];
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,
success: someFunction
});
How do I take a string like:
var t = '<foo><bar>something</bar></foo>';
And convert that to a XML DOM object? cross-browser?
UPDATE: Please see comments to karim79's answer.
Wrap it in a jQuery object. Then use jQuery's normal DOM manipulation methods on it.
var t = $('<foo><bar>something</bar></foo>');
//loop over 'bar' nodes
t.find('bar').each(function () {
alert($(this).text());
});
If you want to convert it back to a plain string (after modifying it for example) you can do it like so:
//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);
}
EDIT: The $.ajax manual says (on the processData option):
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.
So if you're passing a jQuery object to the server, you'll need to set that to true, or omit it altogether (it is set to true by default). Hope that helped.
这篇关于在JavaScript中将字符串转换为XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!