加载Google自定义搜索结果而无需刷新页面 [英] Loading Google Custom Search results without page refresh

查看:79
本文介绍了加载Google自定义搜索结果而无需刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提交一个Google自定义搜索查询,而无需重新加载/刷新整个html页面.我正在使用最新的v2 gcs和仅限结果"布局.

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.

在搜索表单上方的任意位置加载gcs api

Loading the gcs api, anywhere above the Search Form

<script src="//www.google.com/jsapi" type="text/javascript"></script>
<script>
    google.load('search', '1',
        {language : 'en', style : google.loader.themes.V2_DEFAULT});
</script>

我的自定义搜索表单

<form onsubmit="return executeQuery();" id="cse-search-box-form-id">
    <input type="text" name="q" id="cse-search-input-box-id" size="25" autocomplete="off"/>
    <input type="submit" id="site-search-submit" value="search"/>
</form>

gcs结果脚本放置在需要搜索结果的任何地方

The gcs results script placed wherever the search results are wanted

<div id="cse" style="width: 100%;">Loading</div>

<script src="http://www.google.com/jsapi" type="text/javascript"></script>

<script type="text/javascript"> 

    google.load('search', '1', {language : 'en', style : google.loader.themes.V2_DEFAULT});
    google.setOnLoadCallback(function() {
        var customSearchOptions = {};  
        var customSearchControl = new google.search.CustomSearchControl(
       'UNIQUE-API-KEY', customSearchOptions);
        customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
        var options = new google.search.DrawOptions();
        options.setAutoComplete(true);
        options.enableSearchResultsOnly(); 
        customSearchControl.draw('cse', options);
        function parseParamsFromUrl() {
            var params = {};
            var parts = window.location.search.substr(1).split('\x26');
            for (var i = 0; i < parts.length; i++) {
                var keyValuePair = parts[i].split('=');
                var key = decodeURIComponent(keyValuePair[0]);
                params[key] = keyValuePair[1] ?
                    decodeURIComponent(keyValuePair[1].replace(/\+/g, ' ')) :
                    keyValuePair[1];

            }

            return params;

        }

        var urlParams = parseParamsFromUrl();
        var queryParamName = "q";
        if (urlParams[queryParamName]) {
            customSearchControl.execute(urlParams[queryParamName]);

        }

    }, true);

</script>

感谢您的帮助.

谢谢

更新

我已经实现了,

customSearchControl.execute(urlParams[queryParamName]);

现在我的搜索表如下:

<form onsubmit="customSearchControl.execute(urlParams[queryParamName]);" id="cse-search-box-form-id">
    <input type="text" name="q" id="cse-search-input-box-id" size="25" autocomplete="off"/>
    <input type="submit" id="site-search-submit" value="search"/>
</form>

但是,执行搜索仍然会刷新整个页面,这会在启动jquery脚本之前使我最初的html格式陷入混乱.

However, performing a search still refreshes the entire page, which throws my initial html formatting into chaos before jquery scripts are initiated.

谢谢

更新

我以多种组合添加了以下所有变种,但是整个页面都刷新了,或者什么也没有发生.

I've added all varieties of the following in numerous combinations but either the entire page refreshes or nothing happens at all.

<form onsubmit="return executeQuery(); return false;" id="cse-search-box-form-id">

<form onsubmit="executeQuery(); return false;" id="cse-search-box-form-id">

<form onsubmit="return false; executeQuery();" id="cse-search-box-form-id">

<form onsubmit="return false; return executeQuery();" id="cse-search-box-form-id">

<form onsubmit="customSearchControl.execute(urlParams[queryParamName]); return false;" id="cse-search-box-form-id">

<form onsubmit="return executeQuery(); event.preventDefault();" id="cse-search-box-form-id">

<form onsubmit="customSearchControl.execute(urlParams[queryParamName]); event.preventDefault();" id="cse-search-box-form-id">

<form onsubmit="customSearchControl.execute(urlParams[queryParamName]); event.stopPropagation();" id="cse-search-box-form-id">

以此类推...

有人对此有经验吗?进一步定制的json API呢?这样是否可以解决页面刷新的问题?

Anyone have experience with this? What about the json api for further customization? Would that solve the issue of the page refreshing somehow?

谢谢

推荐答案

最好的选择是使用JQuery创建钩子.渲染完成后,下面的以下代码将在 searchButton 仅搜索结果之间创建一个钩子.

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.

为使此设置生效,您需要为元素指定一个gname,否则您将无法通过google.cse.element方法找到它.我有以下代码的实时版本,但我没有做出承诺由于它托管在我的NDSU FTP中,因此将永久存在.

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

这篇关于加载Google自定义搜索结果而无需刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆