Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

javascript - How to use YQL to retrieve web results?

I am having difficulty setting up a simple html file using javascript to display the results of YQL Query.

I understand how to setup the select statement (example: select title,abstract,url from search.web where query="pizza") in the YQL Console. But I don't know how to display it on the html file?

Can somebody help in explaining how to display the results of that statement? Code snippets would be appreciated!

BTW, I've read the YQL Docs but they are somewhat complicated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only way to retrieve YQL results via client-side JavaScript is JSON-P (or by using an additional proxy). Here's a wrapper for the YQL service:

function YQLQuery(query, callback) {
    this.query = query;
    this.callback = callback || function(){};
    this.fetch = function() {

        if (!this.query || !this.callback) {
            throw new Error('YQLQuery.fetch(): Parameters may be undefined');
        }

        var scriptEl = document.createElement('script'),
            uid = 'yql' + +new Date(),
            encodedQuery = encodeURIComponent(this.query.toLowerCase()),
            instance = this;

        YQLQuery[uid] = function(json) {
            instance.callback(json);
            delete YQLQuery[uid];
            document.body.removeChild(scriptEl);
        };

        scriptEl.src = 'http://query.yahooapis.com/v1/public/yql?q='
                     + encodedQuery + '&format=json&callback=YQLQuery.' + uid; 
        document.body.appendChild(scriptEl);

    };
}

Usage:

// Construct your query:
var query = "select * from rss where url='somefeed.com' limit 1";

// Define your callback:
var callback = function(data) {
    var post = data.query.results.item;
    alert(post.title);
};

// Instantiate with the query:
var firstFeedItem = new YQLQuery(query, callback);

// If you're ready then go:
firstFeedItem.fetch(); // Go!!

More info: http://james.padolsey.com/javascript/using-yql-with-jsonp/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...