User:Soumi150/API-Demo.js
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
// API Query to get url of items in a category and display as links.
// Display prompt to take Category as user input.
var input = prompt( 'Please enter category name:', 'Chemistry' ),
/* To get the url of the item pages in a category combine two API calls using generator.
For this query, categorymembers and info have been combined.
*/
url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&origin=*&generator=categorymembers&gcmlimit=20&prop=info&inprop=url';
url = url + '&gcmtitle=Category:' + input;
fetch( url )
.then( function ( response ) { return response.json(); } )
.then( function ( response ) {
var text;
// To check if category was found check whether query property exists in response returned.
if ( response.hasOwnProperty( 'query' ) ) {
var pages = response.query.pages,
items = [], i;
for ( var page in pages ) {
items.push( { pageTitle: pages[ page ].title,
pageUrl: pages[ page ].fullurl
} );
}
text = '<ul>';
text += '<h1>The items in this category are:</h1>';
for ( i = 0; i < items.length; i++ ) {
text += "<li><a href='" + items[ i ].pageUrl + "'>" + items[ i ].pageTitle + '</a></li>';
}
text += '</ul>';
} else {
text = '<h1>No category of the given name was found. Please try again.</h1>';
}
document.getElementById( 'content' ).innerHTML = text;
} )
.catch( function ( error ) {
console.log( error );
} );