Loading Google Custom Search results without page refresh

前端 未结 2 801
深忆病人
深忆病人 2021-01-23 03:52

I would like to submit a google custom search query without reloading/refreshing the entire html page. I\'m using the latest v2 gcs with the \'Results Only\' layout.

Loa

相关标签:
2条回答
  • 2021-01-23 04:21

    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);
    })();
    
    0 讨论(0)
  • 2021-01-23 04:27

    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.

    0 讨论(0)
提交回复
热议问题