【发布时间】:2018-12-12 18:41:28
【问题描述】:
我正在使用 HTTP 请求来获取 Google 的自动完成建议,这就是我这样做的灵感:
您可以向以下 URL 发出 GET 请求:
http://suggestqueries.google.com/complete/search?client=chrome&q=cats
其中“client”参数是您的浏览器名称(适用于大多数浏览器,但您可以传递>相同类型,而不管用户当前使用什么,它仍然可以工作)。
“q”参数是您的搜索字符串。
这将为您返回一个建议项目列表,然后您可以将其放入 jQuery 自动完成插件或构建您自己的(可悲的是,您不能让整个 >google 下拉界面弹出一个函数 :))
(src:Add Google autocomplete to Google search bar?)
我正在使用这个函数来获取谷歌的回复文本:
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”标头?
【问题讨论】:
-
您的 theUrl 是否由网络服务器提供服务?
-
也许
http://suggestqueries.google.com不允许您仅从客户端(浏览器)向服务器(服务器)发出请求 - 这就是它不发送Access-Control-Allow-*标头的原因
标签: javascript xml request cors http-headers