Sep 16, 2010

Use jQuery to add Wikipedia content to your site.


While working on my Political Genome Project site I came across an issue that took a while to figure out how to implement decently. That is to grab Wikipedia data and place it directly on my site. I didn’t want to use any clumsy iFrames or anything. I poked around for a wile and found out that there is actually a nice API for Wiki. The API can pull basically any info you want from any page on Wikipedia.

I wanted to pull the actual description /  article from them and found that by using a url formatted like, , then you will get json data back of the full page. Now throwing this into a jQuery .getJSON request won’t actually work. I found that to get the data back properly for jQuery to use it i had to add &callback=? at the end which turns the url into, . Now with the properly formatted url it was just a matter of dumping the parse text to a div on the page. That worked great and I then ran into another problem. The links were all wanting to point locally.

To fix the problem with the links not actually pointing to wikipedia that was an easy fix. While inside of the .getJSON function I had jQuery loop through and and find all a tags that were not child to the references object and added to the href attribute. Then also just to not take people off my site if they click on a link I had all the links in there also target _blank.

Here’s a code sample of what I did.

In your Header:

  $.getJSON('', function(json) {
    $("#wikiInfo").find("a:not(.references a)").attr("href", function(){ return "" + $(this).attr("href");});
    $("#wikiInfo").find("a").attr("target", "_blank");


In the Body:

<div id="wikiInfo">&nbsp;</div>


Demo of how it works

By FreedomChicken

Twitter Delicious Facebook Digg Stumbleupon Favorites More

Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | stopping spam