How to list Wikipedia page titles with links using JSON?

isopach picture isopach · Jul 12, 2015 · Viewed 9.6k times · Source

This is my current code. It lists out page titles perfectly, but the links all return 'undefined'.

function func(json) {
  var e = document.getElementById('wiki');
  var i;
  for (i=0; i < json.query.allpages.length; i++) {
    e.innerHTML += i + ": " + '<a href="' + "http://en.wikipedia.org/wiki/" +  json.query.link+ '">' +  json.query.allpages[i].title + '</a>' + "<br />";
  }
}

function getFromWikipedia() {
  var txt = document.getElementById('txt');
  var e = document.getElementById('wiki');
  var o = document.createElement("script");
      o.setAttribute("src", "http://en.wikipedia.org/w/api.php?action=query&list=allpages&format=json&apfrom="+txt.value+"&generator=alllinks&callback=func");
  e.appendChild(o);
}

Appending "&prop=links" and/or "&generator=alllinks" to the URL doesn't seem to affect the result.

I would like to know what should I include in this portion:

'<a href="' + json.query.link+ '">'

in order to list the page titles with their respective links. I have tried "json.query.allpages[i].pageID" and "json.query.alllinks" but it has not been working.

Edit: Gave up on finding URL and went to do the pageid method instead.

Solved it with this:

e.innerHTML += i + ": " + '<a href="'+ "http://en.wikipedia.org/wiki/?curid="+  json.query.allpages[i].pageid + '">' +  json.query.allpages[i].title + '</a>' + "<br />";

Answer

schudel picture schudel · Jul 12, 2015

You can create the link directly using the pageid:

function func(json) {
  var e = document.getElementById('wiki');
  var i;
  for (i=0; i < json.query.allpages.length; i++) {
    e.innerHTML += i + ": " + '<a href="' + "http://en.wikipedia.org/?curid=" +  json.query.allpages[i].pageid+ '">' +  json.query.allpages[i].title + '</a>' + "<br />";
  }
}