我使用HTTP请求来获取Google的自动完成建议,这是促使我这样做的原因:
您可以向以下URL发出GET请求:
http://suggestqueries.google.com/complete/search?client=chrome&q=cats
“客户端”参数是您浏览器的名称(大多数浏览器都可以使用,但您可以传递相同的类型,而无需考虑用户当前所处的位置,并且仍然可以使用)。
“ q”参数是您的搜索字符串。
这将为您返回建议项目的列表,然后您可以将其放入jQuery自动完成插件或构建自己的项目(您不能只是整个Google下拉菜单界面,而只能使用单个函数来弹出窗口:)) / p>
(src:Add Google autocomplete to Google search bar?)
我正在使用此功能来获取Google的回复文本:
function httpGetAsync(theUrl, getGoogle){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
getGoogle(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
但是,执行该功能时,CORS似乎阻止了我的回复:Failed to load http://suggestqueries.google.com/complete/search?client=chrome&q=xx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
是否可以在资源中添加“ Access-Control-Allow-Origin”标头?
答案 0 :(得分:2)
除非源具有用于您的域的Access-Control-Allow-Origin标头,否则您不能从用户浏览器向另一个域发出请求。总之,如果不使用某种代理,就无法在用户端发出请求,例如:
https://cors-anywhere.herokuapp.com/
示例:
url: https://cors-anywhere.herokuapp.com/https://google.com