在浏览器中键入此命令会自动下载一个txt文件,该文件是AAPL股票期权数据的json格式文本。
http://www.google.com/finance/option_chain?q=AAPL&output=json
我想把这些数据直接放到一个Javascript变量中,这样我就可以解析结果并在浏览器中显示数据。
我试过了:
$.getJSON('http://www.google.com/finance/option_chain?q=AAPL&output=json', function(json) {
console.log(json);
});但我得到了No 'Access-Control-Allow-Origin' header is present on the requested resource.错误,就像在其他帖子中看到的那样。
我也尝试过使用ajax:
$.ajax({
dataType: "json",
url: "http://www.google.com/finance/option_chain?q=AAPL&output=json",
}).done(function ( data ) {
console.log(data);
});但是得到了相同的错误。
我也尝试过在url中使用jsonp (&output=jsonp),但得到了一个Uncaught SyntaxError: Unexpected token )错误,在Chrome检查器中返回();。
如何将这些json数据从Google直接拉到JS中?
发布于 2017-01-16 23:48:03
我相信有更好的方法...但它是有效的。
首先,要解决跨域请求,您可以使用YQL。则url答案不是有效的json字符串。所以我使用"eval“来执行响应文本,并将其存储在tmp变量中。
function toYQL(site){
return 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent('select * from html where url="' + site + '"') +
'&format=json&callback=?';
}
$.ajax({
dataType: "json",
url: toYQL("http://www.google.com/finance/option_chain?q=AAPL&output=json"),
success: function(response){
eval("var tmp=" + response.query.results.body);
console.log(tmp);
}
})这就对了。
https://stackoverflow.com/questions/41603625
复制相似问题