如何将Google自定义搜索元素与现有表单元素一起使用?

时间:2017-03-28 14:15:39

标签: javascript jquery css search google-custom-search

我正在尝试将我当前的搜索表单与Google的自定义搜索元素一起使用,到目前为止,我无法让它工作。这是我目前的搜索表单。

<form class="search-form" action="/search/">
    <p class="inputs">
        <label for="search-q">Search</label>
        <input type="search" id="search-q" name="search" data-gname="search"placeholder="Find what you're looking for..." value="#formatted_query#">
        <input type="submit" value="Go" class="button postfix brand-orange-bk">
    </p>
</form>

我使用的Google CSE代码段如下所示:

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];

    s.parentNode.insertBefore(gcse, s);

  })();
  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

在结果中(在同一页面上),我有以下内容:

<div class="row">
    <div class="small-12 medium-5 medium-push-7 large-5 large-push-7 columns" id="search-rightcol">
        <section data-searchtab="our-own-knowledgebase" class="search-panel brand-white-bk"></section>
    </div>
    <div class="small-12 medium-7 medium-pull-5 large-7 large-pull-5 columns">
        <div id="google-search-results"></div>
    </div>
</div>

我可以使用gcse:searchbox-only标签而不是我当前的表单,然后我会设置它的样式;但是,当我按下搜索按钮时,它会转到另一个页面,结果不会显示在google-search-results div中。如果我使用gcse:search标签,那么结果将替换当前页面上的所有内容并忽略这行代码:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

我查看了HTML5-valid div tagsCustom Search Element Control API (V2)Using the JavaScript API to render elements,但我不知道如何在我的情况下修改代码,所以我可以简单地通过任何值是在Google CSE代码的输入元素中进行搜索,然后我将结果放在google-search-results div中。在Custom Search Element Control API (V2)的示例中,它显示了以下代码:

var element = google.search.cse.element.getElement('element1);
element.execute('news');

所以我尝试了以下代码,但它没有用......没有结果显示/返回。

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    //var s = document.getElementsByTagName('script')[0];
    var s = google.search.cse.element.getElement('search');

    // do the search:
    var searchTerm = $('##search-q').val();
    s.execute(searchTerm);

    s.parentNode.insertBefore(gcse, s);

  })();

  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

我找到了一个类似的线程(How to use custom search box for google custom search?),但该线程没有解决方案。我还找到了另一个线程(How to style Google Custom Search Engine so that it doesn't display as a block element),但是我对该解决方案的问题是每当我点击搜索时,它会转到另一个页面而忽略此代码:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

非常感谢任何帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

好的,感谢我的同事们,这就是我们解决问题的方法。我把它放在这里也许它可以帮助别人。

searchhelper.perform_google = function(){

    if(typeof(google)!='undefined'){
        google.search.cse.element.render({
            div: "google-search-results",
            tag: 'searchresults-only',
            gname: 'google-results-gname'
        });
        var element = google.search.cse.element.getElement('google-results-gname');
        var query = $('##search-q').val();
        element.execute(query);
    }
};

(function(){
    // add the google custom stuff:
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

window.__gcse = {
  parsetags: 'explicit',
  callback: function(){
    searchhelper.search('all');
  }
};

答案 1 :(得分:0)

在大量调查和搜索之前和之后已经有过这种情况,发现如下: 以下是如何执行此操作的完整示例,您只需使用自己的CSE ID更新它以及在过滤返回结果时可能需要使用的域和部分。

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<title>CSE V2: Custom Search Engine Programarically</title>
<style type="text/css">
h4.warning {color: red;}
h4.recommendation {color: green;}
.gs-image-box , .gs-web-image-box {
  display:none ; 
}
  .gcsc-branding , .gsc-above-wrapper-area {
    display:none ; 
  }
</style>

<!-- Put the following javascript before the closing </head> tag. -->
<script type="text/javascript">
  var searchQuery = "";
  var renderSearchTextboxElement = function() {
    google.search.cse.element.render(
      {
        div: "dynamicTXT1",
		tag: 'searchbox-only',
		gname: 'main-search-button1',
		 attributes: {
          enableAutoComplete: true,
          enableHistory: true,
		  resultsUrl: '/search',
		  queryParameterName: 'q'

		  }
      });
    google.search.cse.element.render(
      {
        div: "dynamicTXT2",
		tag: 'searchbox-only',
		gname: 'main-search-button2',
		 attributes: {
          enableAutoComplete: true,
          enableHistory: true,
		  resultsUrl: '/search',
		  queryParameterName: 'q'

		  }
      });
  }
    var renderSearchElement = function(restructedTo) {
    var as_sitesearchVal = ""; 
    var filtersItems = restructedTo.split(' ');
    if(filtersItems.length == 1){
      as_sitesearchVal = restructedTo;
    }
    var resultlist = google.search.cse.element.getElement('main-searchresults');
    if(resultlist){
      resultlist.clearAllResults();
      document.getElementById("default").innerHTML = "";
    }
    google.search.cse.element.render(
      {
        div: "default",
        tag: 'searchresults-only',
        gname: 'main-searchresults',
        attributes: {
		  queryParameterName: 'q',
          as_oq:restructedTo,
          as_sitesearch:as_sitesearchVal,
		  },
      });
     };
  
  var i = 0
  function executeQuery(filterName) {
    // set textboxes values based on the querystring
    if(searchQuery){
      google.search.cse.element.getElement('main-search-button1').prefillQuery(searchQuery);
      google.search.cse.element.getElement('main-search-button2').prefillQuery(searchQuery);
    }
     console.log(filterName);
     renderSearchElement(filterName);
    console.log(i++);
    if (typeof google != 'undefined' ){
      
      if(!searchQuery){
         if(google.search.cse.element.getElement('main-search-button1').getInputQuery()){
           searchQuery = google.search.cse.element.getElement('main-search-button1').getInputQuery();
         }else if(google.search.cse.element.getElement('main-search-button2').getInputQuery()){
           searchQuery = google.search.cse.element.getElement('main-search-button2').getInputQuery();
         }
      }
      var input = document.getElementById('cse-search-input-box-id');
      var element = google.search.cse.element.getElement('main-searchresults');
      if (searchQuery == '') {
        element.clearAllResults();
      } else {
        element.execute(searchQuery);
      }
      return false;
    }else{
      setTimeout(executeQuery,500);
    }
  }
//  setTimeout(executeQuery,1000);
  
  //document.forms["myform"].submit();
</script>
  <script>
    var myCallback = function() {
    if (document.readyState == 'complete') {
      searchQuery = getParameterByName('q',window.location.href);
      renderSearchTextboxElement();
      executeQuery("");
     
    } else {
      google.setOnLoadCallback(function() {
        renderSearchTextboxElement();
        executeQuery("");
      }, true);
    }
  };
    
 window.__gcse = {
  callback: myCallback
};
  
  (function() {
    var cx = '123:456'; // Insert your own Custom Search engine ID here
    var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = false;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
  })();
    
     function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</head>

<body>
<!-- Search box form -->
  <a href="#" class="" onclick="executeQuery('');" data-filter="people">All</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain.com/section1');" data-filter="section1">section1</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain.com/section2');" data-filter="section2">section2</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain.com/section3 subdomain.your-domain.com ~/your-domain');" data-filter="section3">section3</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain.com/section4');" data-filter="section4">section4</a>
  
  <div id="dynamicTXT1"></div>
  <div id="dynamicTXT2"></div>
  <div id="default"></div>
<form style="display:none" onsubmit="return executeQuery(false);" id="cse-search-box-form-id">
  <!-- This is the input searc box -->
  <input type="text" id="cse-search-input-box-id" data-as_oq="/section1" autocomplete="off" value="energy"/>
  <!-- This is the search button -->
  <input type="submit" value="Search"/>
</form>

<script type="text/javascript"
        src="//www.google.com/cse/brand?form=cse-search-box-form-id&inputbox=cse-search-input-box-id">
</script>
<!-- End of Google branding watermark -->

<!-- Element code snippet -->


<!-- Place this tag where you want the search results to render -->
<hr >
<!-- <gcse:searchresults-only enableOrderBy="false"></gcse:searchresults-only> -->
</body>

</html>
&#13;
&#13;
&#13;