Skip to content

Instantly share code, notes, and snippets.

@ashlynnpai
Created September 14, 2017 14:55
Show Gist options
  • Save ashlynnpai/6cbd60da73bbcd6b76e4bb50529e54b1 to your computer and use it in GitHub Desktop.
Save ashlynnpai/6cbd60da73bbcd6b76e4bb50529e54b1 to your computer and use it in GitHub Desktop.
Wikipedia API viewer
<body>
<input id="startSearch" type="text">
<button onClick="getEntries()">Search Wikipedia</button>
<div>
<button onClick="getRandom()">Get Random Entry</button>
</div>
<div id="showResults">
</div>
</body>
function getEntries() {
$("#showResults").empty();
var keyword = document.getElementById("startSearch").value;
var reorderedList = [];
$.getJSON('https://en.wikipedia.org/w/api.php? action=opensearch&datatype=json&limit=5&search='+keyword+'&callback=?',
function(data) {
var j = 0;
while (j < data[1].length) {
eachItem = [];
for (var i=1; i<data.length; i++) {
eachItem.push(data[i][j]);
};
reorderedList.push(eachItem);
j++;
};
for (var i=0; i<reorderedList.length; i++) {
var description = reorderedList[i][1];
var shortForm = description.slice(0,300);
var title = document.createElement("h1");
var a = document.createElement("a");
var t = document.createTextNode(reorderedList[i][0]);
a.appendChild(t);
a.title = reorderedList[i][0];
a.href = reorderedList[i][2];
title.appendChild(a);
var summary = document.createElement("p");
var u = document.createTextNode(shortForm);
summary.appendChild(u);
$("#showResults").append($(title)).append($(summary));
};
});
};
function getRandom() {
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&explaintext&exintro=&format=json&callback=?", function (data) {
$.each(data.query.pages, function(k, v) {
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids='+v.pageid+'&inprop=url&format=json&callback=?', function(url) {
$.each(url.query.pages, function(key, page) {
var random = document.createElement("h1");
var aRandom = document.createElement("a");
var randomTitle = document.createTextNode(page.title);
aRandom.appendChild(randomTitle);
aRandom.title = page.title;
aRandom.href = page.fullurl;
random.appendChild(aRandom);
$("#showResults").empty().append($(random));
});
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment