如何使用 YQL 检索网页结果? [英] How to use YQL to retrieve web results?

查看:16
本文介绍了如何使用 YQL 检索网页结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我了解如何在 YQL 控制台中设置选择语句(例如:select title,abstract,url from search.web where query="pizza").但是不知道怎么在html文件上显示?

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!

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

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

推荐答案

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

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

    };
}

用法:

// 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!!

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

这篇关于如何使用 YQL 检索网页结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆