Skip to content

Instantly share code, notes, and snippets.

@steren
Created November 18, 2010 02:24
Show Gist options
  • Save steren/704540 to your computer and use it in GitHub Desktop.
Save steren/704540 to your computer and use it in GitHub Desktop.
call Wikipedia API using jQuery and parse result
<div id="insertTest"></div>
<script>
var wikipediaHTMLResult = function(data) {
var readData = $('<div>' + data.parse.text.* + '</div>');
// handle redirects
var redirect = readData.find('li:contains("REDIRECT") a').text();
if(redirect != '') {
callWikipediaAPI(redirect);
return;
}
var box = readData.find('.infobox');
var binomialName = box.find('.binomial').text();
var fishName = box.find('th').first().text();
var imageURL = null;
// Check if page has images
if(data.parse.images.length >= 1) {
imageURL = box.find('img').first().attr('src');
}
$('#insertTest').append('<div><img src="'+ imageURL + '"/>'+ fishName +' <i>('+ binomialName +')</i></div>');
};
function callWikipediaAPI(wikipediaPage) {
// http://www.mediawiki.org/wiki/API:Parsing_wikitext#parse
$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?', {page:wikipediaPage, prop:'text|images', uselang:'en'}, wikipediaHTMLResult);
}
callWikipediaAPI('Aholehole');
</script>
$.getJSON("http://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?", {page:pageName, prop:"text"}, wikipediaHTMLResult);
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&format=json&callback=?", {titles:pageName, prop: "images"}, wikipediaImageResult);
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&format=json&callback=?", {titles:pageName, prop: "revisions", rvprop:"content"}, wikipediaPageResult);
@tjtate
Copy link

tjtate commented Dec 20, 2012

you should change:

data.parse.text.*

to

data.parse.text.["*"]

took me a while to figure out why my browser didnt like the * json object. thanks for posting your work.

@thomasmery
Copy link

thanks indeed!

but here it works with data.parse.text["*"]

extra dot is not necessary I think

@dep-deprecated
Copy link

Have you had any luck getting this to work in Safari? I've not. It gives me:

'''ReferenceError: Can't find variable: jQuery110209405261517968029_1390676300501'''

Interestingly, if I use the web inspector to follow through to wikipedia's api.php, I can see the object trying to come back:

screenshot: https://db.tt/NiTZSg9x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment