`

利用Google AJAX Search API

阅读更多

利用Google AJAX Search API

创建自定义搜索引擎

——Angel

1. 创建自定义搜索引擎插件 1

1.1 问题的提出 1

1.2 问题的分析 3

1.3 问题的求解 4

2. 使用自定义的搜索引擎 16

 

1. 创建自定义搜索引擎插件

1.1 问题的提出

最终效果展示:

【输入技术,点击搜索如下结果】

演示链接:http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/search.html

经常的我们浏览网页会发现人家网站做的搜索功能都相当的强大,不经意间我们也会有相同的想法,是否我们能自己做一个这么强大的搜索功能呢?

很显然如果要自己去研究这么一个搜索引擎算法的话,那么很有可能自己那时候已经鬓发斑白了。所以我们是否能用人家研究的搜索引擎API进行开发,扩展,最终能够用到自己的项目当中,即在原来的基础上进行升级,做成适合自己项目的一个插件,当然最好是适合各个项目,那是会更好了。

1.2 问题的分析

从问题的分析看来,我们需要去选择一个搜索引擎API,而且最好是开源的。经过我们的万里长征,我们最终会发现利用Google Ajax Search API,是一个不错的选择。

那么我们在实战的时候需要准备什么呢?

① jquery-1.4.2.min.js: jquery 库,因为在js中使用了jquery中的提供的一些函数。资源下载地址:

http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

② 文本输入框的背景图:下载地址:

 http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/searchBox.png

③ 搜索按钮背景图片:下载地址:http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/buttons.png

④ 网站Logo图片下载:下载地址:

http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/heading.png

⑤ 其他一些辅助图片下载:

箭头:http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/arrow.png

背景图片:http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/bg.jpg

格式图标:http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/icons.png

更多图片:http://demo.tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/img/more.png

1.3 问题的求解

在进行实战前我们先把开发环境给搭建好:

① 网页制作工具:Dreamweaver,至于使用哪个版本无所谓,或者直接用记事本编辑也可以。

② 浏览器:IE,360,建议没有fixfox的安装一个firefox,因为当有代码错误的时候能够快速进行改正,当然只是建议而已。

万事俱备不欠东风了。Let's get ready to start( 让我们准备开始吧).

① 创建工程

>创建一个文件夹——存放我们的资料,如 Google Search。

>在[Google Search]文件夹下创建以下文件夹及文件:

images文件夹、js文件夹、css文件夹,search.html文件。

>在images下创建search_images,把图片资源放到search_images文件夹下。

> 在css文件夹下创建 google_search_plugin.css文件:存放css代码。

> 在js 文件夹下在创建一个jquery文件夹,然后在把下载的jquery.js放到jquery文件夹下,并且创建一个google_search_plugin.js :存放js代码。

解释:有人也许会有这样的困惑:发现我的文件夹特别多,好像没有这个必要,直接放到根目录下不是更好,或者少建几个目录也行呀。在这边我稍微解释下,基于这么做的一个初衷。我主要是考虑到如果以后写项目的时候要把这个功能直接加到工程里是否方便。我们都知道在实际当中js文件下有很多的js库,所以我们有必要重新创建一个jquery目录来对有关jquery的资源进行分类管理。当然还有等等一些其他的原因,都是个人的一些想法。大家因情况考虑。

当前文件结构:

② 页面编写:

观察我们最终的结果:有一个[输入框 input type="text"] ,一个[按钮 input type="submit"],两个[单选按钮 input type="radio"],还有一个可进行切换搜索格式的,在这里使用ul标签,其他标签也是可以的。代码如下:

<body id="page">

<h1>Google Powered Site Search</h1>

<form id="searchForm">

<fieldset>

     <input type="text"  id="s"/><!-- 输入文本框-->

        <input type="submit" value="Submit" id="submitButton" /><!--提交按钮-->

        <div id="searchInContainer"><!--选择是搜索本地,还是网页搜索-->

          <input type="radio"  id="searchSite" name="check" checked="checked"/><!--搜索站点-->

            <label for="searchSite" id="siteNameLabel">搜索 </label>

            

     <br />

             <input type="radio" value="web" id="searchWeb" name="check"/>

             <label for="searchWeb">搜索网页</label>

        </div>

        <ul class="icons"><!--搜索类型 -->

         <li class="web" title="网页搜索" data-searchType="web">Web</li>

            <li class="images" title="图片搜索" data-searchType="images">Images</li>

            <li class="news" title="新闻搜索" data-searchType="news">News</li>

            <li class="videos" title="视频搜索" data-searchType="video">Videos</li>

        </ul>        

    </fieldset>

</form>

    <!--显示搜索结果-->

    <div id="resultsDiv"></div>

</body>

③ 引入js、css文件

<script type="text/javascript" src="js/jquery/jquery-1.4.2.min.js"></script>

<script  type="text/javascript" src="js/jquery/google_search_plugin.js"></script>

<link type="text/css" rel="stylesheet" href="css/google_search_plugin.css" /> 

④ 编写css代码

打开google_search_plugin.css文件,编写css代码。Css代码主要是控制页面的样式,与功能没有太大的关系。代码如下:

  @charset "UTF-8";

/* CSS Document */

/*任意一个标签的设置*/

*{

margin:0;

padding:0;

}

/*页面的设置*/

body{

font-size:13px;

color:#eee;

font-family:Arial, Helvetica, sans-serif;

background: url(../images/search_images/bg.png) repeat-x #718693;/*整个页面的颜色,可以在此进行修改*/

}

/*body 的 css*/

#page{

/* The main container div */

width:620px;

margin:100px auto 0;

}

/*标题的设置*/

h1{

font-family:Corbel,'Myriad Pro',Arial, Helvetica, sans-serif;

background:url(../images/search_images/heading.png) no-repeat center top;

text-indent:-9999px;

overflow:hidden;

height:90px;

}

/*表单css*/

form#searchForm{

background-color:#4C5A65; /*背景颜色,通过这个属性可以更改文本框和searchButton周围的眼睛颜色*/

 padding:50px 50px 30px; /*fieldset这个组的内边距*/

 margin:80px 0; /*上边距和下边距为80,左右边距为0,这个可以控制form表单到网页顶部的距离。*/

 position:relative; /*form表单里的组件是相对form表单进行摆放*/

 

 /*圆角属性-不过很遗憾不兼容ie,在fiefox浏览器就可以看到效果,<br />

       参看文章:http://blog.sina.com.cn/s/blog_681b3a420100si81.html

 */

 -moz-border-radius:16px;

 -webkit-border-radius:16px;  

     border-radius:16px;

}

/*fieldset css*/

fieldset{

border:none;/*默认fieldset四边是有边框的.,*/

}

/*文本框text 的css*/

input#s{

background: url(../images/search_images/searchBox.png) no-repeat;/*背景图片*/

border:none;/*去掉边框*/

color:#888888;/*字体颜色*/

float:left;/*往左漂浮*/

font-family:Arial,Helvetica,sans-serif; /*字体样式*/

font-size:15px;  /*字体大小*/

height:36px; /*高度*/

line-height:36px; /*行高*/

margin-right:12px; /*和按钮直接的距离*/

outline:medium none;

padding:0 0 0 35px;/*上0 右0 下0 左35*/

text-shadow:1px 1px 0 white;

width:385px;/*宽度*/

}

/*ul设置 */

.icons{ 

list-style:none;/*列表样式,即去掉前面的符号样式*/

 margin:10px 0 0 335px; /*距离左边的边距*/

 height:19px; /*高度*/

 position:relative;

}

.icons li{  

 background: url(../images/search_images/icons.png) no-repeat;  /*背景图片*/

 float:left;  

 height:19px;  

 text-indent:-999px; /*文本缩进,当图片显示不了的时候,可以显示文字*/ 

 cursor:pointer;  

 margin-right:5px;  

}  

/* Styling each icon */

li.web{ width:15px;}

li.web.active,

li.web:hover{ background-position:left bottom;}

li.images{ width:22px; background-position:-18px 0;}

li.images.active,

li.images:hover{ background-position:-18px bottom;}

li.news{ width:14px; background-position:-44px 0;}

li.news.active,

li.news:hover{ background-position:-44px bottom;}

li.videos{ width:17px; background-position:right 0;}

li.videos.active,

li.videos:hover{ background-position:right bottom;}

/*设置点击时候的箭头*/

span.arrow{

width:11px;

height:6px;

margin:21px 0 0 5px;

position:absolute;

background: url(../images/search_images/arrow.png) no-repeat;

left:0;

}

/*提交按钮*/

#submitButton{

background: url(../images/search_images/buttons.png) no-repeat;

width:83px;

height:36px;

text-indent:-9999px;

overflow:hidden;/*溢出部分隐藏*/

text-transform:uppercase;/*将单词全部转换成大写的*/

border:none;

cursor:pointer;

}

#submitButton:hover{/*鼠标经过的按钮的时候*/

background-position:left bottom;

}

/*搜索类型*/

div#searchInContainer{

float:left;

margin-top:12px;

width:330px;

}

/*标签*/

label{

color:#DDDDDD;

cursor:pointer;

font-size:11px;

position:relative;

right:-2px;

top:-2px;

margin-right:10px;

white-space:nowrap;

/*float:left;*/

}

/*属性选择器*/

input[type=radio]{

cursor:pointer;

/*float:left;*/

}

/*在js中动态加入的一个div标签*/

.pageContainer{

/* Holds each page with search results. Has an inset bottom border. */

border-bottom:1px solid #5e7481;

margin-bottom:50px;

/* Adding a dark bottom border with box shadow */

-moz-box-shadow:0 1px 0 #798e9c;

-webkit-box-shadow:0 1px 0 #798e9c;

box-shadow:0 1px 0 #798e9c;

}

p.notFound{

text-align:center;

padding:0 0 40px;

}

/*存放结果的div*/

.webResult{ text-shadow:1px 1px 0 #586a75;margin-bottom:50px;}

.webResult h2{/**/ 

background-color:#5D6F7B;

font-size:18px;

font-weight:normal;

padding:8px 20px;

/* Applying CSS3 rounded corners */

-moz-border-radius:18px;

-webkit-border-radius:18px;

border-radius:18px;

}

.webResult h2 b{ color:#fff; }

.webResult h2 a{ color:#eee;border:none;}

.webResult p{ line-height:1.5;padding:15px 20px;}

.webResult p b{ color:white;}

.webResult > a{ margin-left:20px;}

/* Image & video search results */

.imageResult{

float:left;

height:180px;

margin:0 0 20px 40px;

text-align:center;

width:152px;

overflow:hidden;

}

.imageResult img{ display:block;border:none;}

.imageResult a.pic{

border:1px solid #fff;

outline:1px solid #777;

display:block;

margin:0 auto 15px;

}

/* The show more button */

#more{

width:83px;

height:24px;

background: url(../images/search_images/more.png) no-repeat;

cursor:pointer;

margin:40px auto;

}

#more:hover{

background-position:left bottom;

}

/* Giving Credit */

p.credit{

margin:20px 0;

text-align:center;

}

p.credit a{

background-color:#4B5A64;

border:1px solid;

border-color:#3D4D57 #788E9B #788E9B #3D4D57;

color:#c0d0d8;

font-size:10px;

padding:4px 8px;

text-shadow:1px 1px 0 #38464F;

}

p.credit a:hover{

background-color:#38464f;

border-color:#38464f #788E9B #788E9B #38464f;

}

a, a:visited {

text-decoration:none;

outline:none;

border-bottom:1px dotted #97cae6;

color:#97cae6;

}

a:hover{

border-bottom:1px dashed transparent;

}

.clear{

clear:both;

}

  

⑤ 编写js

这是程序的核心。代码如下:

//JavaScript Document

  $(document).ready(function(){/*====windown.onload = function(){}*/

  

   var config = {/*JSON数组,一些基本设置*/

   siteURL : 'www.iteye.com/',//: 'tutorialzine.com',//搜索的网站

   searchSite : true,

   type : 'web',

   append : false,

   perPage : 8, // A maximum of 8 is allowed by Google: 每页显示的数目

   page : 0 // The start page:起始页---从0开始

   }

  

   // The small arrow that marks the active search icon:

   var arrow = $('<span>',{className:'arrow'}).appendTo('ul.icons');/*-- 在选择搜索类型的地方的下边那个箭头---*/

  

   $('ul.icons li').click(function(){/*点击ul 下的li的事件*/

   var el = $(this);

  

   if(el.hasClass('active')){/*判断是否是有active class ,如果有的话,直接返回*/

   // The icon is already active, exit

   return false;

   }

  

   el.siblings().removeClass('active');/*移除原先的class ,再次加入*/

   el.addClass('active');

  

   // Move the arrow below this icon

   arrow.stop().animate({/*动画效果*/

   left : el.position().left,

   marginLeft : (el.width()/2)-4

   });

  

   // Set the search type

   config.type = el.attr('data-searchType');

   $('#more').fadeOut();

   });

  

   // Adding the site domain as a label for the first radio button:

   $('#siteNameLabel').append(' '+config.siteURL);/*在标签上进行追加*/

  

   // Marking the Search tutorialzine.com radio as active:

   $('#searchSite').click(); /*点击事件*/

  

   // Marking the web search icon as active:

   $('li.web').click();

  

   // Focusing the input text box:

   $('#s').focus();/*焦点事件*/

   $('#searchForm').submit(function(){/*提交事件*/

   googleSearch();

   return false;

   });

  

   $('#searchSite,#searchWeb').change(function(){

   // Listening for a click on one of the radio buttons.

   // config.searchSite is either true or false.

  

   config.searchSite = this.id == 'searchSite';

   });

  

   /*这是核心方法*/

   function googleSearch(settings){

  

   // If no parameters are supplied to the function,

   // it takes its defaults from the config object above:

  

   settings = $.extend({},config,settings);

   settings.term = settings.term || $('#s').val();

  

   if(settings.searchSite){

   // Using the Google site:example.com to limit the search to a

   // specific domain:

   settings.term = 'site:'+settings.siteURL+' '+settings.term;

   }

  

   // URL of Google's AJAX search API

   var apiURL = 'http://ajax.googleapis.com/ajax/services/search/'+settings.type+'?v=1.0&callback=?';

   var resultsDiv = $('#resultsDiv');

  

   $.getJSON(apiURL,{q:settings.term,rsz:settings.perPage,start:settings.page*settings.perPage},function(r){

  

   var results = r.responseData.results;

   $('#more').remove();

  

   if(results.length){

  

   // If results were returned, add them to a pageContainer div,

   // after which append them to the #resultsDiv:

  

   var pageContainer = $('<div>',{className:'pageContainer'});

  

   for(var i=0;i<results.length;i++){

   // Creating a new result object and firing its toString method:

   pageContainer.append(new result(results[i]) + '');

   }

  

   if(!settings.append){

   // This is executed when running a new search, 

   // instead of clicking on the More button:

   resultsDiv.empty();

   }

  

   pageContainer.append('<div class="clear"></div>')

    .hide().appendTo(resultsDiv)

    .fadeIn('slow');

  

   var cursor = r.responseData.cursor;

  

   // Checking if there are more pages with results, 

   // and deciding whether to show the More button:

  

   if( +cursor.estimatedResultCount > (settings.page+1)*settings.perPage){

   $('<div>',{id:'more'}).appendTo(resultsDiv).click(function(){

   googleSearch({append:true,page:settings.page+1});

   $(this).fadeOut();

   });

   }

   }

   else {

  

   // No results were found for this search.

  

   resultsDiv.empty();

   $('<p>',{className:'notFound',html:'没有搜索到任何结果!'}).hide().appendTo(resultsDiv).fadeIn();

   }

   });

   }

  

   /*显示结果*/

   function result(r){

  

   // This is class definition. Object of this class are created for

   // each result. The markup is generated by the .toString() method.

  

   var arr = [];

  

   // GsearchResultClass is passed by the google API

   switch(r.GsearchResultClass){

   case 'GwebSearch':

   arr = [

   '<div class="webResult">',

   '<h2><a href="',r.unescapedUrl,'" target="_blank">',r.title,'</a></h2>',

   '<p>',r.content,'</p>',

   '<a href="',r.unescapedUrl,'" target="_blank">',r.visibleUrl,'</a>',

   '</div>'

   ];

   break;

   case 'GimageSearch':

   arr = [

   '<div class="imageResult">',

   '<a target="_blank" href="',r.unescapedUrl,'" title="',r.titleNoFormatting,'" class="pic" style="width:',r.tbWidth,'px;height:',r.tbHeight,'px;">',

   '<img src="',r.tbUrl,'" width="',r.tbWidth,'" height="',r.tbHeight,'" /></a>',

   '<div class="clear"></div>','<a href="',r.originalContextUrl,'" target="_blank">',r.visibleUrl,'</a>',

   '</div>'

   ];

   break;

   case 'GvideoSearch':

   arr = [

   '<div class="imageResult">',

   '<a target="_blank" href="',r.url,'" title="',r.titleNoFormatting,'" class="pic" style="width:150px;height:auto;">',

   '<img src="',r.tbUrl,'" width="100%" /></a>',

   '<div class="clear"></div>','<a href="',r.originalContextUrl,'" target="_blank">',r.publisher,'</a>',

   '</div>'

   ];

   break;

   case 'GnewsSearch':

   arr = [

   '<div class="webResult">',

   '<h2><a href="',r.unescapedUrl,'" target="_blank">',r.title,'</a></h2>',

   '<p>',r.content,'</p>',

   '<a href="',r.unescapedUrl,'" target="_blank">',r.publisher,'</a>',

   '</div>'

   ];

   break;

   }

  

   // The toString method.

   this.toString = function(){

   return arr.join('');

   }

   }

  

  

  });

在浏览器就可以看到效果了。

2. 使用自定义的搜索引擎

这就是我们自己的一套东西了,当我们下次再使用的时候就非常的方便了,只需要修改一下google_search_plugin.js里的config的网址就OK了。

参考文章:

http://tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/

<!--EndFragment-->

0
1
分享到:
评论

相关推荐

    Google AJAX Search API

    The Map Search Control is a simple to use application of the Google AJAX Search API that is designed to let you easily add a searchable map to your pages, sites, and blogs. The control on the right ...

    掌握 Ajax第 9 部分-使用 Google Ajax Search API.pdf

    掌握 Ajax第 9 部分-使用 Google Ajax Search API.pdf

    Google AJAX Search API+TAG

    Google AJAX Search API+TAG ,想学习的朋友进来看看........

    掌握Ajax系列9:使用Google Ajax Search API

    其实也可以与一些公共API,例如来自Google或 Amazon的API进行通信,从而为Web应用程序增加您自己的脚本和服务器端程序所不能提供的更多功能。本文教您如何向公共API,例如Google提供的API发出请求并接收其响应。

    用PHP获取Google AJAX Search API 数据的代码

    用PHP获取Google AJAX Search API 数据的代码

    Google-AJAX-Search-API.rar

    Google-AJAX-Search-API.rar

    用Google AJAX Search API对互联网上Linux命令出现次数排名

    NULL 博文链接:https://codingstandards.iteye.com/blog/798861

    AJax详解.chm

    第 9 部分: 使用 Google Ajax Search API 第 10 部分: 使用 JSON 进行数据传输 第 11 部分:将 Ajax 带入 Eclipse 的 Ajax Toolkit Framework 的两个工具 第 12 部分:面向 Java 开发人员的 Ajax: 构建动态的 Java...

    Google AJAX 搜索 API实现代码

    Google AJAX 搜索 API文档:http://code.google.com/intl/zh-CN/apis/websearch/docs/ 代码如下:&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Google AJAX 搜索 API&lt;/title&gt; &lt;style type=”...

    掌握Ajax,第9部分:使用GoogleAjaxSearchAPI

    火龙果软件工程技术中心 本文内容包括:使用公共API使用GoogleAjaxSearchAPI的准备工作最简单的Google搜索Web应用程序Ajax在哪里?深度探索Google的AjaxSearchAPI结束语参考资料发出异步请求并不意味着只是与您自己...

    Ajax详解.rar

    1.2 使用 Google Ajax Search API 的准备工作 101 1.3 Google 的 API 文档 104 1.4 最简单的 Google 搜索 Web 应用程序 104 1.5 Ajax 在哪里? 109 1.6 深度探索 Google 的 Ajax Search API 111 第 10 部分: ...

    Ajax-google-maps-search.zip

    Ajax-google-maps-search.zip,techtonic项目:google maps zipcode搜索使用api和ajax请求,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中...

    ajax IBM 官方资料 非常不错

    第 1 部分: Ajax 简介 第 2 部分: 使用 JavaScript 和 Ajax 发出异步请求 第 3 部分 XMLHttpRequest 对象 第 4 部分: 利用 DOM 进行 ...第 9 部分: 使用 Google Ajax Search API 第 10 部分: 使用 JSON 进行数据传输

    元搜索引擎search.zip

    应用领域:1、采集人物信息2、采集电子报纸3、使用NekoHTML和XPath解析百度搜索返回结果4、使用JSoup和CSSPath解析百度搜索返回结果5、使用Google AJAX API获取谷歌搜索结果 标签:search

    Professional Ajax

    Maps and Mashups with Geocoding, Google Maps API and Yahoo! Maps API Ajax Debugging with FireBug and Microsoft FiddlerASP.NET AJAX Extensions (formerly code-named “Atlas”) And of course the Second...

    XMLHttpRequest手册

    压缩包“ajax.rar”内含:“《掌握Ajax.chm》”和...掌握 Ajax,第 9 部分: 使用 Google Ajax Search API http://www.ibm.com/developerworks/cn/web/wa-ajaxintro9/ 掌握 Ajax,第 10 部分: 使用 JSON 进行数据传输 ...

    Google.rar_DEMO_dwr_gis java_google

    google的search的api 以及其demo 使用ajax的 dwr+prototype技术实现

    Google Hacking for Penetration Testers

    Learn more about the AJAX Search API, Calendar, Blogger, Blog Search, and more. About the Author Johnny Long is a "clean-living" family guy who just so happens to like hacking stuff. Over the past two...

Global site tag (gtag.js) - Google Analytics