0. TLDR
这是一个工作小提琴 http://jsfiddle.net/8h7yowxb/1/使用谷歌的https://suggestqueries.google.com/complete/search https://suggestqueries.google.com/complete/search
参数:
output/client # "toolbar" => xml, "firefox" => json, "chrome" => jsonp
ds # which site to search in ("bo" for books, "yt" for youtube...)
q # search term: "sher"
Query:
Results:
["sher",["sherlock holmes","sherrilyn kenyon","sherman alexie","sheryl sandberg","sherlock","sherlock holmes short stories","sherlock holmes book","sher o shayari","sherlock holmes novels","sher shah suri"]]
1. 建议与搜索结果
首先要认识到的是,当谷歌提出建议时,它们并不是你按回车键时它会显示的结果。
搜索结果如果您的查询中包含相关术语,则该术语是相关的。
建议假设您的查询不完整,因此将您的查询与其他查询进行比较,以猜测查询的完整版本可能是什么。
当我搜索“sher”时http://books.google.com http://books.google.com我看到的结果是:
- 以色列-巴勒斯坦和平谈判,1999-2001
- 超越中立:完美主义与政治
- Desert
- 拒绝选择!:利用你所有的兴趣、激情……
其原因是author:前三个是“George Sher”,第四个是“Barbara Sher”。这是理想的行为,因为当我搜索“sher”时,我不希望“Sherlock”结果埋葬“George Sher”。
2. 解决方案
谷歌也有一种API来提供建议。关于它的一些信息可以在这里找到 http://shreyaschand.com/blog/2013/01/03/google-autocomplete-api/。更重要的是,使用开发者工具,您可以准确地看到 Google 正在做什么。
Using Developer Tools: Inspect the https://books.google.com https://books.google.com page (CTRL+SHIFT+i in Chrome). Go to the network tab and wait until everything is loaded.
当您开始输入时,Google 会向服务器发出请求,您将看到该请求填充在列表中。当我输入“sher”时,Google 发送了以下请求:
https://suggestqueries.google.com/complete/search?client=books&ds=bo&q=sher&callback=_callbacks_._1id33zyi5
查看变量:
client = books
ds = bo
q = sher
callback = _callbacks_._1id33zyi5
-
client确定您收到的结果类型(XML [工具栏]、JSON [firefox]、JSONP [chrome])
-
ds将搜索限制在特定站点(书籍 [bo]、youtube [yt] 等)。
-
q当然是查询文本
-
callback是用于 JSONP 的参数(它有一些与 JSON 的重要区别 http://json-jsonp-tutorial.craic.com/index.html)。不用太担心,因为 jQuery 可以为您处理这个问题。
我通过查看此请求并阅读,将有关这些参数的信息拼凑在一起this http://shreyaschand.com/blog/2013/01/03/google-autocomplete-api/ and this http://agichevski.com/2014/06/10/google-search-autocomplete-api/.
CORS:因为您是从不是 google.com 的域发出请求,所以您将得到一个Access-Control-Allow-Origin
错误。这是一项试图防止的安全措施XSS https://en.wikipedia.org/wiki/Cross-site_scripting。为了解决这个问题,您需要使用 JSONP。
使用 jQuery,我们不需要担心回调,所以让我们将客户端参数更改为chrome
并使用最终查询:
下面的工作示例:在此示例中,您可能需要注意"google:suggestrelevance"
key,这是使用 JSONP 的额外好处(Google 仅在 JSONP 数据中返回该信息)。
var requestUrl = "https://suggestqueries.google.com/complete/search?client=chrome&ds=bo&q=";
var xhr;
$(document).on("input", "#query", function () {
typewatch(function () {
// Here's the bit that matters
var queryTerm = $("#query").val();
$("#indicator").show();
if (xhr != null) xhr.abort();
xhr = $.ajax({
url: requestUrl + queryTerm,
dataType: "jsonp",
success: function (response) {
$("#indicator").hide();
$("#response").html(syntaxHighlight(response));
}
});
}, 500);
});
/*
* --------- YOU ONLY NEED WHAT IS ABOVE THIS LINE ---------
*/
$(document).ready(function () {
$("#indicator").hide();
});
// Just for fun, some syntax highlighting...
// Credit: http://stackoverflow.com/a/7220510/123415
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
// And automatic searching (when you stop typing)
// Credit: http://stackoverflow.com/a/2219966/123415
var typewatch = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
/*
* Safe to ignore:
* This is just to make stuff look vaguely decent
*/
body {
padding: 10px;
}
div * {
vertical-align: top;
}
#indicator {
display: inline-block;
background: no-repeat center/100% url('http://galafrica.actstudio.ro/img/busy_indicator.gif');
width: 17px;
height: 17px;
margin: 3px;
}
/*
*
* CREDIT:
* http://stackoverflow.com/a/7220510/123415
*/
pre {
outline: 1px solid #ccc;
padding: 5px;
}
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: red;
}
.key {
color: #008;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type=text id="query" placeholder="Start typing..." /><span id="indicator"></span>
</div>
<pre id="response"></pre>