2009-07-24 10 views
4

私はYQLクエリの結果を表示するためにjavascriptを使用して簡単なhtmlファイルを設定するのが難しいです。YQLを使用してWeb検索結果を取得するにはどうすればよいですか?

私はYQLコンソールでselect文(例:select title、abstract、url from search.web where query = "pizza")を設定する方法を理解しています。しかし、私はhtmlファイルに表示する方法を知らないのですか?

誰かがそのステートメントの結果を表示する方法を説明するのに役立つことができますか? コードスニペットをいただければ幸いです!

私はYQLドキュメントを読んだことがありますが、やや複雑です。

答えて

8

クライアント側のJavaScript経由でYQL結果を取得する唯一の方法は、JSON-P(または追加のプロキシを使用)です。

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

    }; 
} 

使用法:ここではYQLサービスのラッパーだ

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

+0

どのように私はこの方法でdatatables.org内のテーブルを使用することができますから、非常に最初のニュース記事を取得ん:!私はそれがYQLのウェブサイトを使用して作ったのですか? – juanpastas

2

ここではあなたのための非常に簡単な例です。

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

すべてのそれはそれはヤフーのフロントページ

関連する問題