I have the following Ajax that uses the Wikipedia API to return a jsonp result for Bon Jovi:
var wikiUrl = 'Bon_Jovi';
function getAbout(wikiUrl){
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=' + wikiUrl,
dataType: 'jsonp',
success: function (data) {
console.log(data);
}
});
}
The data response is as follows:
>Object {warnings: Object, query: Object}
>query: Object
>normalized: Array[1]
>pages: Object
>63123: Object
>extract: "<p><b>Bon Jovi</b> is an American rock band...</p>"
How can I select the extract
and save it as a string? var extractText = data.query.pages[0].extract
returns query
as an undefined error.
pages
is an object, not an array. In this case, the data is under the 63123
property. Unless you know this property before-hand, you would need to iterate over the properties.
var wikiUrl = 'Bon_Jovi';
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=' + wikiUrl,
dataType: 'jsonp',
success: function (data) {
var pages = data.query.pages;
for (var p in pages) {
if(pages.hasOwnProperty(p)) {
console.log(pages[p].extract);
}
}
}
});