【问题标题】:How to use YQL to retrieve web results?如何使用 YQL 检索网页结果?
【发布时间】:2010-11-13 16:23:35
【问题描述】:

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

我了解如何在 YQL 控制台中设置选择语句(例如:从 search.web where query="pizza" 中选择标题、摘要、url)。但是不知道怎么在html文件上显示?

有人可以帮助解释如何显示该语句的结果吗? 代码 sn-ps 将不胜感激!

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

【问题讨论】:

    标签: javascript html search yql


    【解决方案1】:

    通过客户端 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);
    
        };
    }
    

    用法:

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

    【讨论】:

    • 如何通过这种方法使用 datatables.org 中的表?
    【解决方案2】:

    这是给你的一个小例子。我使用 YQL 网站制作的:

    <html>  
      <head>       
      </head>  
      <body>   
        <script>  
          function top_stories(o){ 
            // parse through the output here:
            var items = o.query.results.item;
            // do whatever you want with the output here:  
            console.log(items[0].title);
          }  
        </script> 
        <script src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&diagnostics=false&callback=top_stories'></script>  
      </body>  
    </html>
    

    它从 Yahoo! 的首页获得了第一个新闻报道

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多