我很難用javascript設置一個簡單的html文件來顯示YQL Query的結果。如何使用YQL檢索網頁結果?
我明白如何在YQL控制檯中設置select語句(例如:select,title,abstract,url from search.web where query =「pizza」)。但我不知道如何在html文件中顯示它?
有人可以幫助解釋如何顯示該聲明的結果嗎? 代碼片斷將不勝感激!
順便說一句,我讀過YQL文檔,但它們有點複雜。
我很難用javascript設置一個簡單的html文件來顯示YQL Query的結果。如何使用YQL檢索網頁結果?
我明白如何在YQL控制檯中設置select語句(例如:select,title,abstract,url from search.web where query =「pizza」)。但我不知道如何在html文件中顯示它?
有人可以幫助解釋如何顯示該聲明的結果嗎? 代碼片斷將不勝感激!
順便說一句,我讀過YQL文檔,但它們有點複雜。
通過客戶端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/
這是給你一個很簡單的例子。我做了使用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>
所做的只是從雅虎頭版
我怎麼能使用表中datatables.org用這種方法得到的第一個新聞故事!? – juanpastas 2013-04-11 23:32:20