Loading Google Custom Search results without page refresh

筅森魡賤 提交于 2019-12-02 08:08:06

you need to call

customSearchControl.execute(urlParams[queryParamName]);

whenever you need to search. so use that function in onsubmit on form.

while solving this problem, I have setup it on my own website. you can check it out here.

Basically I just add submit handler to form via jquery and did all the work that google was doing inside the submit handler. works flawlessly.

Best option is to use JQuery to create hooks. The following code below will create a hook between the searchButton and the searchresults-only when the render is complete.

In order for this setup to work, you need to specify a gname for your element, otherwise you will not be able to find it through the google.cse.element methods. I have a live version of the code below, but I don't make promises that will be permamently live since it is hosted in my NDSU FTP.

Index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Google Search Customization</title>
    <script src="https://code.jquery.com/jquery-1.12.1.js"></script>
    <script src="index.js"></script>
  </head>
  <body>
    <h1>Trigger an Element API v2 search through a custom textbox</h1>
    <label>Enter Search Query:</label><input id="customSearchText" type="text">
    <input id="customSearch" type="submit">
    <div style="width: 50%; float: right;">
      <gcse:searchresults-only gname="searchOnlyCSE"></gcse:searchresults-only>
    </div>
  </body>
</html>

index.js

//Hook a callback into the rendered Google Search. From my understanding, this is possible because the outermost rendered div has id of "___gcse_0".
window.__gcse = {
  callback: googleCSELoaded
}; 
function googleCSELoaded() {
  // The hook in question.
  $("#customSearch").click(function() {
    var searchText = $("#customSearchText").val();
    console.log(searchText);
    var element = google.search.cse.element.getElement('searchOnlyCSE');
    element.execute(searchText);
  })
}

// CSE Code. This is a free version, so please don't make too many requests.
(function() {
  var cx = '001386805071419863133:cb1vfab8b4y';
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!