jQuery運用Google Search API搜索結果保存到本地

Google Search API的接口目前是一個返回JSON格式的WebService。

如:http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback=?

本案例使用到文件有三個:

search.html——一個簡單查詢頁面

styles.css——與查詢頁面相配的css樣式表

script.js——調用Google Search API,獲取結果集,輸入到查詢頁面中容器

img文件夾——存放圖標文件


search.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Google Powered Site Search | Tutorialzine Demo</title>

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

</head>

<body>

<div id="page">

    <h1>Google Powered Site Search</h1>
    
    <form id="searchForm" method="post">
		<fieldset>
        
           	<input id="s" type="text" />
            
            <input type="submit" value="Submit" id="submitButton" />
            
            <div id="searchInContainer">
                <input type="radio" name="check" value="site" id="searchSite" checked />
                <label for="searchSite" id="siteNameLabel">Search</label>
                
                <input type="radio" name="check" value="web" id="searchWeb" />
                <label for="searchWeb">Search The Web</label>
			</div>
                        
            <ul class="icons">
                <li class="web" title="Web Search" data-searchType="web">Web</li>
                <li class="images" title="Image Search" data-searchType="images">Images</li>
                <li class="news" title="News Search" data-searchType="news">News</li>
                <li class="videos" title="Video Search" data-searchType="video">Videos</li>
            </ul>
            
        </fieldset>
    </form>

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

<!-- It would be great if you leave the link back to the tutorial. Thanks! -->
<p class="credit"><a href="http://tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/">Powered by Tzine & Google</a></p>
    
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>

styles.css

*{
	margin:0;
	padding:0;
}

body{
	font-size:13px;
	color:#eee;
	font-family:Arial, Helvetica, sans-serif;
	background:url('img/bg.jpg') repeat-x #718693;
}

#page{
	/* The main container div */
	width:620px;
	margin:100px auto 0;
}

h1{
	font-family:Corbel,'Myriad Pro',Arial, Helvetica, sans-serif;
	background:url('img/heading.png') no-repeat center top;
	text-indent:-9999px;
	overflow:hidden;
	height:90px;
}

#searchForm{
	/* The search form. */
	background-color:#4C5A65;
	padding:50px 50px 30px;
	margin:80px 0;
	position:relative;

	-moz-border-radius:16px;
	-webkit-border-radius:16px;
	border-radius:16px;
}

fieldset{
	border:none;
}

#searchInputContainer{
	/* This div contains the transparent search box */
	width:420px;
	height:36px;
	background:url("img/searchBox.png") no-repeat;
	float:left;
	margin-right:12px;
}

#s{
	/* The search text box. */
	
	border:none;
	color:#888888;
	background:url("img/searchBox.png") no-repeat;
	
	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;
	text-shadow:1px 1px 0 white;
	width:385px;
}

/* The UL that contains the search type icons */

.icons{
	list-style:none;
	margin:10px 0 0 335px;
	height:19px;
	position:relative;
}

.icons li{
	background:url("img/icons.png") no-repeat;
	float:left;
	height:19px;
	text-indent:-9999px;
	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{
	/* The little arrow that moves below the icons */
	
	width:11px;
	height:6px;
	margin:21px 0 0 5px;
	position:absolute;
	background:url('img/arrow.png') no-repeat;
	left:0;
}


/* The submit button */


#submitButton{
	background:url('img/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;
}


/* The Search tutorialzine.com / Search the Web radio buttons */


#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;*/
}


/* Styling the search results */


.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;
}


/* Web & news results */


.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('img/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;
}


script.js

$(document).ready(function(){
	
	var config = {
		siteURL		: 'tutorialzine.com',	// Change this to your site
		searchSite	: true,
		type		: 'web',
		append		: false,
		perPage		: 8,			// A maximum of 8 is allowed by Google
		page		: 0				// The start page
	}
	
	// The small arrow that marks the active search icon:
	var arrow = $('<span>',{className:'arrow'}).appendTo('ul.icons');
	
	$('ul.icons li').click(function(){
		var el = $(this);
		
		if(el.hasClass('active')){
			// The icon is already active, exit
			return false;
		}
		
		el.siblings().removeClass('active');
		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=?';
		//alert(apiURL);
		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:'No Results Were Found!'}).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('');
		}
	}
	
	
});

以上的文件結構應該如下:


發佈了57 篇原創文章 · 獲贊 6 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章