2013-04-09 56 views
0

JS维基百科API返回:读取XML使用jQuery

$.ajax({ 
    type: "GET", 
    url: "http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=pie&prop=revisions&rvprop=content", 
    dataType: "xml", 
    success: function(xmlData){ 
     var totalNodes = $('*',xmlData).length; // count XML nodes 
     alert("This XML file has " + totalNodes); 
    }, 
    error: function(){ 
     alert("Could not retrieve XML file."); 
    } 
}); 

不知道我的问题是什么;谁能帮忙?我提供的URL是返回的'pie'wiki页面的XML。您应该可以将其输入到浏览器并查看它。但是,当我运行此代码时,我从错误函数中获得警报,但未成功。任何想法表示赞赏!谢谢。

+0

您确实违反了[同源策略](http://en.wikipedia.org/wiki/Same_origin_policy),是不是? – Bergi 2013-04-09 19:46:45

回答

0

该问题出现在跨域来源策略中,您无法通过获取xml文件来解决该问题。我建议切换到JSON,因为dataType: 'jsonp'用于跨域请求。您的代码将改成这样:

$.ajax({ 
    type: "GET", 
    url: "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=pie&prop=revisions&rvprop=content", 
    dataType: "jsonp", 
    success: function(jsonData){ 
     //var totalNodes = $('*',xmlData).length; // count XML nodes 
     //alert("This XML file has " + totalNodes); 
     console.log(jsonData); 
    }, 
    error: function(){ 
     alert("Could not retrieve data."); 
    } 
}); 

这样你就不需要解析xml因为你已经得到一个Javascript Object