2017-01-12 58 views
0

在瀏覽器中鍵入此值會自動下載一個txt文件,該文件是json格式的AAPL股票期權數據文本。致電Google財經期權API網址

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({ 
    dataType: "json", 
    url: "http://www.google.com/finance/option_chain?q=AAPL&output=json", 
}).done(function (data) { 
    console.log(data); 
}); 

,但得到了同樣的錯誤。

我也嘗試過使用jsonp(&output=jsonp)在url中,但得到一個Uncaught SyntaxError: Unexpected token)錯誤,它在Chrome檢查器中返回();

我該如何將這個json數據從Google直接拖入JS?

+0

嘗試使用'https://'而不是'http://' –

+0

我不再收到錯誤,但沒有數據被拉出,控制檯中沒有任何內容被打印。謝謝 – brno792

+0

如果您想獲取數據,請嘗試將成功函數放入Ajax對象中。 Ajax返回後,它將轉到成功函數而不是done函數。 Ajax將首先執行done函數,因爲它是一種異步方法。 –

回答

0

我相信有更好的方法來做到這一點......但它的工作原理。

首先,要解決跨域請求,您可以使用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); 
    } 
}) 

你走了。

+0

您的腳本可以通過SQL注入輕鬆入侵,並且沒有必要也沒有理由使用其他API來調用另一個API。 –

+0

「我確定有更好的方法來做到這一點......但它有效。」 然後提出一個解決方案 – EteriuS