Last active
December 29, 2015 21:18
-
-
Save wragge/7728954 to your computer and use it in GitHub Desktop.
Get a random newspaper article from the Trove API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function(){ | |
var trove_api_key = "Your API key"; // Add your API key | |
var trove_api_url = "http://api.trove.nla.gov.au/result?zone=newspaper"; | |
var start_year = 1803; | |
var end_year = 1954; | |
var current_year = 0; | |
function get_random_article() { | |
current_year = get_random_year(); // Get a random year first to limit the query size | |
var query = trove_api_url + "&q=date:[" + current_year + " TO " + current_year + "]&n=0&l-category=Article&encoding=json&key=" + trove_api_key; | |
get_api_result(query, 'total'); | |
} | |
function get_api_result(query, type) { | |
$.ajax({ | |
"dataType": "jsonp", | |
"url": query, | |
"success": function(results) { | |
process_results(results, type); | |
} | |
}); | |
} | |
function process_results(results, type) { | |
if (type == 'total') { | |
var total = results.response.zone[0].records.total; | |
var number = Math.floor(Math.random() * total); // Get one random result from the total set | |
var query = trove_api_url + "&q=date:[" + current_year + " TO " + current_year + "]&s=" + number + "&n=1&l-category=Article&encoding=json&key=" + trove_api_key; | |
get_api_result(query, 'article'); | |
} else if (type == 'article') { | |
var article = results.response.zone[0].records.article[0]; | |
// Do something with the returned article | |
} | |
} | |
function get_random_year() { | |
var range = (end_year - start_year) + 1; | |
var year = start_year + Math.floor(Math.random() * range); | |
return year; | |
} | |
get_random_article(); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment