0

This is the wikipedia link for the "wiki search" and callback "wikipedia".

http://en.wikipedia.org/w/api.php?action=opensearch&search=wiki&callback=wikipedia

I use something like the following

function wikipedia(w){
   alert(w)
}

This gives me the autosuggestions, but it gives me whole code. Is there any javascript code that can call, for example the first result of this json.

I have tried many like the following

w[1]
w.wiki[0]

but no success.

AMD
  • 1,278
  • 4
  • 15
  • 33
  • 1
    The link shows a function wikipedia(the data); does 'w' in your code means the same data with the function and all? – luckystars Feb 07 '13 at 22:04
  • Also found why I got the error "Uncaught TypeError: Cannot read property '1' of undefined ", that was because the code was written badly and the function was called (two times) one was before the data were received from wikipedia – AMD Feb 07 '13 at 22:31

4 Answers4

3

The list of suggestions is available in w[1], and you need to iterate through that list to do something with it.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

you have to parse this JSON string into an object, if you know jQuery you can try this

pwolaq
  • 6,343
  • 19
  • 45
2

If w[1] is throwing that error like you say, there is probably something else wrong with your code. If you can use jQuery I'd strongly recommend it for jsonp. This code does what you ask:

http://jsfiddle.net/Hg4KJ/

$.ajax({
    url: 'http://en.wikipedia.org/w/api.php?action=opensearch&search=wiki&callback=wikipedia',
    dataType: 'jsonp',
    callback: 'wikipedia'
}).done(function(w){
    var items = w[1];

    for(var i = 0, il = items.length; i < il; i++){
        console.log(items[i]);
    }
});
joeltine
  • 1,610
  • 17
  • 23
1

Try this

function wikipedia(w) {
    "use strict";
    var j = w;//JSON.parse(w); as commented, no need to parse.
    alert(j[1]);
}

If you're not using jQuery anyway.

romo
  • 1,990
  • 11
  • 10
  • 2
    Since it's JSON-P, `w` is actually not a string containing JSON but already an object. Just have a look at the link. – Felix Kling Feb 07 '13 at 22:16