如何在Jquery中显示维基百科的json数据

时间:2014-02-21 01:17:32

标签: javascript jquery json wikipedia-api

我想在维基百科的这个JSON结果表单的“extract:”:......中显示文本

{
    "query": {
        "normalized": [
            {
                "from": "india",
                "to": "India"
            }
        ],
        "pages": {
            "14533": {
                "pageid": 14533,
                "ns": 0,
                "title": "India",
                "extract": "<p><b>India</b> (/\u02c8\u026andi\u0259/), officially the <b>Republic of India</b> (<i>Bharat Ganrajya</i>), is a country in South Asia. It is the seventh-largest country by area, the second-most populous country with over 1.2 billion people, and the most populous democracy in the world.</p>"
            }
        }
    }
}

这就是我所做的但失败了:

url1 ="https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exsentences=2&titles=india&format=json&callback=?";
$.getJSON(url1,function(result) {
    $.each(result.query, function(i,q) {
        $.each(q.pages, function(i,p) {
            $.each(p, function(i,j) {  
                content = '<p>' + j.extract  + '</p>';
                $(content).appendTo("#input");
            });
        });
    });

请纠正我

1 个答案:

答案 0 :(得分:0)

你正在循环

  • result.query,将使用normalizedpages进行回调 - 不必要
  • pages - 这没关系
  • p,可以回复pageidnstitle等您不想要的内容。

而是直接访问这些属性并使用

var url1 = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exsentences=2&titles=india&format=json&callback=?";
$.getJSON(url1, function(result){
    $.each(result.query.pages, function(i,p){
        var content = p.extract;
        $(content).appendTo("#input");
    });
});