返回顶部

收藏

使用jQuery整合Google搜索API到站内搜索

更多

作者:Terry li -GBin1.com网站搜索经常是web开发者需要处理的功能之一,很多网站都放弃自己开发搜索引擎,一是因为需要开发周期,二是因为耗费 自己站点服务器资源,所以大家最常用的方式是整合google自定义的搜索服务,但是肯定有广告,并且界面设计非常有限。这里我参考了一些文章,使用jQuery整合 了Google搜索API,实现了自己的站内搜索功能,使用还比较方便,毕竟自己处理页面元素。站内搜素演示原文出处:使用jQuery来整合Google搜索API 到你自己的网站

[JavaScript]代码

$(document).ready(function(){

    var config = {
        siteURL     : 'gbin1.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(){
        $('#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]
        );
    }

    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:

                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:'找不到和您的查询 "<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('');
        }
    }

});

标签:jQuery

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 廖雪峰 发表 2017-11-11 10:58:00 使用jQuery实现图片懒加载原理
  2. 博主 发表 2018-05-16 00:12:00 jQuery - 回车发送消息提交表单
  3. 博主 发表 2012-05-24 00:00:00 10 个技巧助你写出卓越的 jQuery 插件
  4. 博主 发表 2013-11-25 00:00:00 高效 jquery 的奥秘
  5. 博主 发表 2013-11-25 00:00:00 高效 jquery 的奥秘
  6. 博主 发表 2013-11-25 00:00:00 高效 jquery 的奥秘
  7. Flying 发表 2015-08-13 16:45:59 使用ocLazyLoad实现AngularJS模块按需懒加载
  8. 王思捷 发表 2016-09-06 15:20:59 Underscore对于object的extend之坑
  9. Leon 发表 2018-03-28 14:10:00 本地使用js或jquery操作cookie在谷歌浏览器chrome中不生效
  10. 博主 发表 2017-09-28 01:50:55 jQuery 性能优化技巧
  11. 博主 发表 2013-07-29 00:00:00 jquery add element in the html dom
  12. 博主 发表 2013-07-29 00:00:00 jquery add element in the html dom

发表评论