javascript|yahoo|搜尋引擎 美國東部時間3月1日,雅虎公司聯合創始人之一的楊致遠將宣布公司的搜尋網路將進入Web服務。雅虎公司在
www.developer.yahoo.com網站建立了Yahoo Search Developer Network,公司計劃在此紐約舉行的搜尋引擎戰略大會(Search Engine Strategies Conference)上推出這一計劃。該網路將允許開發人員在雅虎搜尋之上建立新的應用程式,其中包括映像、視頻、新聞以及地區搜尋等內容。想要使用這項服務的會員必須先去
http://api.search.yahoo.com/webservices/register_application 申請一個自已的ID號,註:每個ID號每天只能搜尋5000次。
下面我們看一下,如何用javascript指令碼調用Yahoo! Search API實現搜尋的效果,全部指令碼如下:
/*
* yahoo_search_api.js
* Part of the Yahoo! Search Sidebar for Firefox
* powered by Yahoo! Search web services (http://api.search.yahoo.com)
* Written by Marc Abramowitz (http://marc.abramowitz.info)
* Copyright (C) 2005 Yahoo! Inc.
* www.knowsky.com
*/
function Yahoo_Search() {}
Yahoo_Search.baseURL = function () {
return "http://api.search.yahoo.com/WebSearchService/V1/";
}
Yahoo_Search.appid = function () {
return "YahooSearchSidebar";
}
Yahoo_Search.baseArgs = function () {
return "appid=" + this.appid();
}
Yahoo_Search.Results = function (args) {
var xmlUrl = this.baseURL() + "webSearch?"
+ this.baseArgs()
+ "&query=" + args["Doc"]
+ "&zip="
+ "&start=" + args["First"]
+ "&results=" + args["Count"];
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlUrl, false);
xmlhttp.send(null);
return this.readXML(xmlhttp.responseXML);
}
Yahoo_Search.readXML = function (xmlDoc) {
try {
var retVal = new Array();
var resultSet = xmlDoc.getElementsByTagName("ResultSet")[0];
var totalResultsAvailable = parseInt(resultSet.getAttribute("totalResultsAvailable"));
var totalResultsReturned = parseInt(resultSet.getAttribute("totalResultsReturned"));
var firstResultPosition = parseInt(resultSet.getAttribute("firstResultPosition"));
var start = firstResultPosition;
var end = firstResultPosition + totalResultsReturned - 1;
var results = xmlDoc.getElementsByTagName("Result");
for (var i = 0; i < results.length; i++) {
var result = results[i];
var title = result.getElementsByTagName('Title')[0].firstChild.nodeValue;
var summary = '';
if (result.getElementsByTagName('Summary')[0].firstChild) {
summary = result.getElementsByTagName('Summary')[0].firstChild.nodeValue;
}
var clickUrl = result.getElementsByTagName('ClickUrl')[0].firstChild.nodeValue;
var url = result.getElementsByTagName('Url')[0].firstChild.nodeValue;
retVal[i] = { I: start + i, Title: title, Summary: summary, ClickUrl: clickUrl, Url: url };
}
return retVal;
} catch(exception) {
alert('Exception occurred while reading XML (i=' + i + '; start=' + start + ';end=' + end + '): ' + exception);
}
}
有興趣的朋友還可以看一下由[動態網站製作指南]所製作的ASP版本:http://www.knowsky.com/yahoo/