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

How to use Google Custom Search Element with existing form element?

我正在尝试将我当前的搜索表单与 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 tags, Custom Search Element Control API (V2), and Using the JavaScript API to render elements but I'm unclear as to how I would go about modifying the code in my situation so I can simply pass whatever value is in the input element to the Google CSE code to do the search and then I'll put the result in the google-search-results div. In the example of the Custom Search Element Control API (V2),它显示了这个代码:

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

所以我尝试了下面的代码但是它没有用...没有结果是 showing/returning.

(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?) but there is no resolution to that thread. I have also found another thread (),但我对该解决方案的问题是每当我单击搜索时,它都会转到另一个页面而忽略此代码:

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

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

好的,感谢我的同事,我们就是这样解决的。我把它放在这里也许对其他人有帮助。

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');
  }
};

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

<!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>