Calling finance.yahoo api using jquery

一曲冷凌霜 提交于 2019-12-01 10:31:24

问题


I want to send http request for fetching finance.yahoo stock data with url like : http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp which returns a csv file. I want to read the response data and fill it in a listview using Javascript or JQuery mobile. None of the links I referred helped me.

I tried using the following code:

$.ajax({
    type: "GET",
    url: "http://finance.yahoo.com/d/quotes.csv",
    data: "s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp",
    dataType: "text/csv",
    success: function(data) {
        alert(JSON.stringify('data is :' + data));
    }
});

I get blank data as alert. Any sample code or useful link would be appreciated.


回答1:


I think that the problem is the request is cross domain. There is another question about this here:

Cross-Domain get CSV file

and another answer here :Yahoo JSONP Ajax Request Wrapped in callback function

and a working example here: Displaying ajax results from yahoo finance using underscore.js

Here is a working jsfiddle which makes a jsonp request to d.yimg.com to get the data http://jsfiddle.net/gp6zL/

    YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
        alert(JSON.stringify(data));
    };
    var query;
    query = 'Google';
    if (query.length > 0) {

        $.ajax({
            type: "GET",
            url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
            data: {
                query: query
            },
            dataType: "jsonp",
            jsonp: "callback",
            jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
        });
    }



回答2:


I try to take jQuery out of the equation. The following code will work as long as you whitelist "finance.yahoo.com".

var request = new XMLHttpRequest();
request.open("GET", "http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp", true);
request.onreadystatechange = function() {//Call a function when the state changes.
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 0) {
            console.log(request.responseText);
        }
    }
}
request.send();


来源:https://stackoverflow.com/questions/15637057/calling-finance-yahoo-api-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!