jQuery调用谷歌API的网站搜索

jQuery调用谷歌API的网站搜索266
HTML
可以从HTML标记开始。从新的HTML5 doctype,我们继续定义文档的标题和包括样式表的头部部分页面。
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>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
在身体部分,我们主要的div容器元素——#页面。里面的形式,不仅是一个搜索表单,但是作为一个容器。 CSS3圆角,深色的背景颜色应用,这使得它更容易与页面的其余部分区分开来。 在表单的文本输入框,在哪个电台组搜索当前网站/网页,和四个搜索类型图标,组成了一个无序列表。最后我们包括jQuery和脚本。js,在本教程的最后一步讨论。 CSS 位于styles.css CSS样式。只有更有趣的部分被包含在这里。
#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;
}

#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;
}
如前所述,表单的功能不仅限于只提交数据,但也作为常规的容器元素。这让页面上的标记最小,同时还提供丰富的功能。 文本输入框,#年代风格的背景图片和填充,因此文本不包含放大镜。
.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:-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{
	/* 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;
}
在上面的片段中,您可以看到搜索类型图标都共享一个背景图像。它与背景位置偏移的适当部分所示,默认和徘徊状态。 相同的技术用于submit按钮。与消极- indent隐藏它的文本,按钮。png是显示为背景,图像的顶部部分可见默认和底部徘徊。
.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:170px;
	margin:0 0 20px 40px;
	text-align:center;
	width:150px;
}
.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;
}
jQuery 正如一开始所提到的,这个应用程序使用谷歌的AJAX搜索API。谷歌提供自己的JavaScript库,但是如果您选择使用它,你是受限的他们的用户界面。功能,它可能不是你想要的提供你的访客。这就是为什么在本教程中,我们使用的是“裸版”通过发行JSONP电话直接与jQuery API。 在我们开始讨论jQuery代码之前,我们看到谷歌的数据提供给我们,当我们运行一个搜索API。
$(document).ready(function(){

	var config = {
		siteURL		: 'jqueryfuns.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=?';
		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 uted 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();
			}
		});
	}
googleSearch()函数将JSONp请求发送给Google的API,生成结果的标记,并将它插入# resultsDiv div。 它可以空div事先(如果我们是在做一个新的搜索)或附加结果(这种情况当我们点击“更多”按钮)。 两个路径遵循相同的逻辑——一个新的。 pageContainer div为每组创建的结果(这个div底部边界,所以更容易区分一个页面的结果从隔壁),结果类的对象(你可以看到下面的这个类),初始化及其标记添加到pageContainer。 配置这个程序来搜索你的网站真的很简单

也许你还喜欢