Google AJAX Search 簡單範例
九月 12, 2008
首先要到 http://code.google.com/apis/ajaxsearch/signup.html 申請 AJAX Search API Key ,如果你已經申請過 Google Map API Key 可以直接使用兩者是相同的。
只要一個 DIV 就能有 Google Search 的大部份功能!
Google API
- GSearchControl
- GsearcherOptions
預設只顯示第一個結果,加上 GSearchControl.EXPAND_MODE_OPEN 就會自動展開結果。 - GwebSearch
setUserDefinedClassSuffix 可以附加結果欄中的 css名稱。 - 若要用程式執行查詢功能可用:
searchControl.execute(關鍵字);
程式碼
<script src="http://maps.google.com/jsapi?key="
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
google.load("search", "1");
google.setOnLoadCallback(initialize);
var map = null;
function initialize() {
// 建立一個搜尋控制項
var searchControl = new google.search.SearchControl();
// 指定展開搜尋結果
var options = new GsearcherOptions();
//options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// 建立一個網站搜尋
var siteSearch = new GwebSearch();
siteSearch.setUserDefinedLabel("Horn Network");
siteSearch.setUserDefinedClassSuffix("hn");
siteSearch.setSiteRestriction("http://klcin.tw/net");
searchControl.addSearcher(siteSearch, options);
// 建立一個網站搜尋
siteSearch = new GwebSearch();
siteSearch.setUserDefinedLabel("Horn Library");
siteSearch.setUserDefinedClassSuffix("hl");
siteSearch.setSiteRestriction("http://klcin.tw/book");
searchControl.addSearcher(siteSearch, options);
// Tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));
}
</script>
[body]
<div id="searchcontrol" style="width:100%;"></div>
[/body]
參考資料: