使用JQuery解析Ajax xml响应

时间:2014-06-29 12:00:26

标签: jquery ajax xml parsing

我正在尝试使用JQuery解析xml文档。 xml是通过Ajax请求获得的:

$.ajax({
    url: address,
type: 'GET',
dataType: 'xml',
success: function(data) {
    console.log(data);
    }

});

如果我将请求放在浏览器上,我会得到这样的回复:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<root>
  <c>208</c>
    <lst>
      <s>
        <id>92</id>
        <t>3</t>
        <ot>06,00</ot>
        <ct>21,30</ct>
        <cat>Electronics</cat>
      </s>
...

现在,我尝试了几种方法来解析xml响应,例如我尝试使用标记't'登录控制台元素,但我没有成功。

我试过,成功了:

var tag = $(data).find('t');
console.log(tag);

但这给了我一个空数组

这个解决方案也给了我一个空数组:

var parser=new DOMParser();
var xmlDoc=parser.parseFromString(data.responseText,"text/xml");
console.log(xmlDoc);
console.log($(xmlDoc).find('t'));

有谁知道解析这个xml文档的正确方法吗?

1 个答案:

答案 0 :(得分:1)

解决了,问题是我试图以错误的方式发出跨域XML请求。这段代码对我有用:

var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + address + '"') + '&format=xml&callback=?';

    // Request that YSQL string, and run a callback function.
    // Pass a defined function to prevent cache-busting.
    $.getJSON(yql, function (data) {
        var xml = data.results[0];
        console.log(xml);
        console.log($(xml).find('t')[0].innerHTML);

    });

我希望这可以帮助其他人解决同样的问题

相关问题