Loading Google Custom Search results without page refresh

前端 未结 2 795
深忆病人
深忆病人 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

    
    
      
        Google Search Customization
        
        
      
      
        

    Trigger an Element API v2 search through a custom textbox

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

提交回复
热议问题