我是计算机科学大学一年级的学生,作为一个业余项目,我正在尝试制作一个使用 Google 趋势数据的小网站。如果可能的话,我只想使用 JQuery/JavaScript。
我正在尝试获取当您访问该 URL 时 Google 趋势提供的 JSON。我打算稍后使用该数据来确定每个术语(name1 和 name2)的平均值和当前值。我正在 MAMP 本地主机服务器上运行此代码。我的预期结果就是您直接访问它时看到的 JSON。但是,我在浏览器控制台中收到以下响应:
"XMLHttpRequest cannot load [URL]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access."
可以获取这些数据吗?如果是这样怎么办?如果我正确理解该错误,Google 将禁止检索该资源。如果无法获取该数据,有哪些可能的解决方法?
$(function() {
$.ajax({
url: 'http://www.google.com/trends/fetchComponent?q='+name1+','+name2+'&cid=TIMESERIES_GRAPH_0&export=3',
type: 'GET',
dataType: 'json',
//headers: '[Does something go here?]',
success: function(data, status, xhr)
{
console.log(data);
},
error: function(xhr, status, error)
{
console.log("Error: " + status + " " + error);
}
});
});
附注对于任何冒犯,我深表歉意...我真的不知道自己在做什么。
最佳答案
我刚刚使用了您给定的网址
https://www.google.com/trends/fetchComponent?q=asdf,qwerty&cid=TIMESERIES_GRAPH_0&export=3
将 q=asdf,qwerty 分别替换为您的 name1 和 name2。
这将返回 json 数据
运行代码片段后可以看到
google.load('visualization', '1');
google.setOnLoadCallback(queryInit);
function queryInit() {
var url = 'https://www.google.com/trends/fetchComponent?q=asdf,qwerty&cid=TIMESERIES_GRAPH_0&export=3';
var query = new google.visualization.Query(url)
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
$('#divdata').text(JSON.stringify(response))
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.2.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="divdata">
</div>
关于javascript - JQuery AJAX header 和 Google 趋势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37893115/