2013-11-02 31 views
1

鑑於WikipediaAPI,一篇文章的在英文維基百科的標題,我上午網址提供回JSON:JS&WikipediaAPI:檢索文章的介紹?

var url = "http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=Unicorn&prop=extracts&exsentences=10&explaintext&format=json"; 

的迴應是這樣的:

{ 
    "query": { 
     "pages": { 
      "ramdom_number_here": { 
       "pageid": ramdom_number_here, 
       "ns": 0, 
       "title": "Unicorn", 
       "extract": "The unicorn is a legendary animal that has been described since antiquity as a beast with a large, pointed, spiraling horn projecting from its forehead." 
      } 
     } 
    } 
} 

鑑於<ramdom_number_here>每篇文章的變化因此是不可預測的。

如何把握extracttitle的值重用呢?

回答

3

它主要是攻擊API的好網址,一個JQuery $ .getJSON和一個詼諧的技巧來傳遞該項目的ID。在那裏,使用Object.keys(data)[x]用Object.keys(data)[i]替換名義路徑的數據座標。

  • Object.keys(data) - 給你在該級別的密鑰列表。
  • 然後使用i =您的目標數據的數字範圍。對於第一個數據點,對於我們[i] = [0]。

方案>JSfiddle

function WD(item) { 
    url = "http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=" + item.toString() + "&prop=extracts&exintro&explaintext&format=json&redirects&callback=?"; 
    $.getJSON(url, function (json) { 
     var item_id = Object.keys(json.query.pages)[0]; // THIS DO THE TRICK ! 
     sent = json.query.pages[item_id].extract; 
     result = "<b>En :</b> <t>" + item + "</t> <b>⇒</b> " + sent; 
     $('#anchor1').append("<div>"+result+"</div>"); // transformation 
    }); 
} 
WD("Dragon"); 

對於一些擴展,var list = ["dragon", "Unicorn", "Cat"],包裝用$.each()功能,一些快速的CSS,我得到一個優雅而又簡單的結果,例如:

​​

如果您需要html,請刪除&explaintext。深入瞭解Wikipedia API以獲取更多功能。

鼓勵+1歡迎。