Question

I apologize in advance if this is the wrong place to post this sort of thing, but here we go:

Here is the code I'm currently implementing on my webiste (Thanks to charlietfl for this code)

$(document).ready(function(){
    var url='http://query.yahooapis.com/v1/public/yql?q=select * from html where url=\'https://stackoverflow.com/\'and xpath=\'//div[@id="question-mini-list"]//h3//a\'&format=json&callback=?';    
    $.getJSON( url, function(data){
        $.each(data.query.results.a, function(){ 
            $('#stack').append('<td><a href="http://stackoverflow.com'+this.href +'">'+this.content+'</a></td>')           
        })
    })
});

I hate to use code I don't fully understand, So here is my questions:

In the 'var url' in the query, he uses @id="question-mini-list". I looked in the html of stackoverflow, and there is nothing by that name (closest I got was a class named 'question-hyperlink'), so why does that work?

Second: In the 'each', data.query.results.a I don't see 'query' or 'results' used anywhere else, so how I know to use those?.

Last question: at the end of your 'url' why 'callback=?' ?

Thank you so much! :)

Était-ce utile?

La solution 2

You'd be amazed what you can find when you Google something!

I don't know anything about XPath, but I noticed that the @id you're asking with was associated with something about XPath:

xpath=\'//div[@id="question-mini-list"]

I Googled 'XPath' and found a page that explains that @id is shorthand for selecting the 'id' attribute of the context node.

Now, I do happen to know a little bit about the next two points in your question, but if I didn't, I'm sure Google would have told me that .getJSON() returns a data object. From the query, I can deduct that the object's structure is something like:

data: {
    query: {
        results: {
            a: // something
        }
    }
}

You would either know in advance to use data.query.results.a or you can discover the data object's structure using the console.

Google would also point me to documentation about JSON callbacks that explain that question mark syntax.

Autres conseils

  1. If you view source on stackoverflow.com you'll see this:

    <div id="question-mini-list">

    <h3><a href="/questions/....">...</a></h3>

    ...

  2. The YQL result JSON object looks like:

    { query: { results: { a: [ ... ] } } }

  3. Apparently callback needs to be set to get JSON output.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top