v5tech / notes

notes
https://ameizi.gitee.io/notes
MIT License
1.53k stars 378 forks source link

Google站内搜索API示例 #115

Open v5tech opened 8 years ago

v5tech commented 8 years ago

搜索页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>西安交通大学网络公开课-搜索</title>
    <link rel="stylesheet" type="text/css" href="http://oc.xjtu.edu.cn/style/style.css"/>
    <link rel="stylesheet" type="text/css" href="http://oc.xjtu.edu.cn/css/search.css"/>
    <style rel="stylesheet" type="text/css">
    .backToTop {
        display: none;
        width: 18px;
        line-height: 1.2;
        padding: 5px 0;
        background-color: #000;
        color: #fff;
        font-size: 12px;
        text-align: center;
        position: fixed;
        _position: absolute;
        right: 10px;
        bottom: 100px;
        _bottom: "auto";
        cursor: pointer;
        opacity: .6;
        filter: Alpha(opacity=60);
    }
   </style>
</head>
<body>
<div id="content">
    <div id="site-search">
        <div class="site-search-hd">
            <form id="searchForm" method="post">
                <fieldset>
                    <legend>站内搜索</legend>
                    <input id="s" type="text" />
                    <input id="localsearch" type="hidden" value="1">
                    <button type="submit" id="submitButton"><span class="visuallyhidden">搜索</span></button>
                    <div class="search-tabs">
                        <div id="searchInContainer" style="padding-left: 50px;">
                            <input type="radio" name="check" value="site" id="searchSite" checked />
                            <label for="searchSite" id="siteNameLabel">搜索</label>
                            <input type="radio" name="check" value="web" id="searchWeb"/>
                            <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>
                    </div>
                </fieldset>
            </form>
        </div>
        <div id="resultsDiv"></div>
    </div>
</div>
<script type="text/javascript" src="http://oc.xjtu.edu.cn/js/libs/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="http://oc.xjtu.edu.cn/js/search.js"></script>
<script type="text/javascript">
//实现返回顶部的功能
(function() {
    var $backToTopTxt = "返回顶部", $backToTopEle = $('<div class="backToTop"></div>').appendTo($("body"))
        .text($backToTopTxt).attr("title", $backToTopTxt).click(function() {
            $("html, body").animate({ scrollTop: 0 }, 120);
    }), $backToTopFun = function() {
        var st = $(document).scrollTop(), winh = $(window).height();
        (st > 0)? $backToTopEle.show(): $backToTopEle.hide();    
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);    
        }
    };
    $(window).bind("scroll", $backToTopFun);
    $(function() { $backToTopFun(); });
})();
</script>
</body>
</html>

search.js(Google API封装)

$(document).ready(function(){

    var config = {
        siteURL     : 'oc.xjtu.edu.cn/',    // 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
    }

    var scrollsettings;

    // 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(){
        //window.location.href = window.location.pathname + "?s=" +  $('#s').val();

        $('#localsearch').val("1");
        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 getURLParameter(name) {
        return decodeURI(
            (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
        );
    }

    $(window).scroll(function(){
        if($("#more").is(":visible")==true){
            if ($(window).scrollTop() == $(document).height() - $(window).height() ){                   
                googleSearch({append:true,page:scrollsettings.page+1});
                //googleSearch();
                return false;
            }
        }
    });     

    if(getURLParameter("s")!=null){
        $('#localsearch').val("0");
        googleSearch();
        return false;
    }

    function googleSearch(settings){

        // If no parameters are supplied to the function,
        // it takes its defaults from the config object above:

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

        var urls = getURLParameter("s");

        //alert(urls);

        if($('#localsearch').val()==0){;
            if(urls=='null'){
                settings.term = settings.term || $('#s').val("");
                $('#s').val("");
                return;
            }else{
                settings.term = urls;
                $('#s').val(urls);
            }
        }else if($('#localsearch').val()==1){;
            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:
                //alert('estimatedResultCount:' + cursor.estimatedResultCount + " " + 'settings.page' +(settings.page+1));

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

                    $('<div>',{id:'more'}).appendTo(resultsDiv).click(function(){
                        googleSearch({append:true,page:settings.page+1});
                        $(this).fadeOut();
                    });

                }

                scrollsettings = settings;
            }
            else {

                // No results were found for this search.

                resultsDiv.empty();
                $('<p>',{className:'notFound',html:'找不到和您的查询 "<b>' + $('#s').val() + '</b>" 相符的内容或信息。'}).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('');
        }
    }

});