0

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.

alias51
  • 8,178
  • 22
  • 94
  • 166

2 Answers2

1

try:

var extractText = data.query.pages[63123].extract
8t'
  • 11
  • 1
  • 2
1

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.

Example:

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);
        }
      }
    }
});
Community
  • 1
  • 1
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171