如何使用YQL检索Web结果?

chr*_*ris 4 html javascript search yql

我很难使用javascript设置一个简单的html文件来显示YQL查询的结果.

我理解如何在YQL控制台中设置select语句(例如:从search.web中选择title,abstract,url,其中query ="pizza").但我不知道如何在html文件中显示它?

有人可以帮忙解释如何显示该陈述的结果吗?代码片段将不胜感激!

顺便说一句,我已经阅读了YQL文档,但它们有点复杂.

Jam*_*mes 8

通过客户端JavaScript检索YQL结果的唯一方法是JSON-P(或使用其他代理).这是YQL服务的包装器:

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);

    };
}
Run Code Online (Sandbox Code Playgroud)

用法:

// 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!!
Run Code Online (Sandbox Code Playgroud)

更多信息:http://james.padolsey.com/javascript/using-yql-with-jsonp/