Skip to content

Instantly share code, notes, and snippets.

@wragge
Last active December 29, 2015 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wragge/7728954 to your computer and use it in GitHub Desktop.
Save wragge/7728954 to your computer and use it in GitHub Desktop.
Get a random newspaper article from the Trove API.
$(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