在 JavaScript 中将字符串转换为 XML 文档 [英] Convert String to XML Document in JavaScript

查看:49
本文介绍了在 JavaScript 中将字符串转换为 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ajax 的 jQuery 示例页面上看到了这个示例:

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

然后将其转换为 XML DOM 对象?跨浏览器?

And convert that to a XML DOM object? cross-browser?

更新:请参阅对 karim79 回答的评论.

UPDATE: Please see comments to karim79's answer.

推荐答案

将其包装在 jQuery 对象中.然后使用jQuery的普通DOM操作方法就可以了.

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

$.ajax 手册说(关于 processData 选项):

The $.ajax manual says (on the processData option):

默认情况下,数据传入到数据选项作为一个对象(技术上,字符串以外的任何东西)将是处理并转换为查询字符串,适合默认内容类型应用程序/x-www-form-urlencoded".如果你想发送 DOMDocuments,或者其他未处理的数据,设置这个选项为 false.

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默认情况下).希望有所帮助.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆