【问题标题】:Reading XML returned from Wikipedia API using jQuery使用 jQuery 读取从 Wikipedia API 返回的 XML
【发布时间】:2013-04-01 09:44:43
【问题描述】:

JS:

$.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。您应该能够将其输入浏览器并查看它。但是,当我运行此代码时,我从错误函数中得到警报,而不是成功。任何想法表示赞赏!谢谢。

【问题讨论】:

标签: jquery xml api mediawiki


【解决方案1】:

问题出在跨域源策略中,您无法通过获取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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 2011-11-03
    • 2018-10-16
    相关资源
    最近更新 更多