0

我正在创建一个简单的股票代码,其中符号最终将通过 cms 输入。到目前为止,我已经成功地正确获取了 ajax 数据,我试图弄清楚如何将每个符号及其对应的数据拆分为单独的项目、列表项目或其他任何内容。我尝试使用 .each 但没有运气。

这是我的js:

(function(){
var getStocks = (function(){

    var initialize = function(){
        _setListeners();
    };

    var _setListeners = function(){

            var symbol = ["GOOG", "AAPL", "A", "AA", "ABT"];

        $.ajax({
            url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D"+symbol+"%26f%3Dnsl1d1t1c1ohgv%26e%3D.csv'%20and%20columns%3D'name%2Csymbol%2Clast_trade_price%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2'&format=json",
            dataType: 'json',
        success: function(data) { 
            console.log(data);
            var name = data.query.results.row.name;
            var last_trade = data.query.results.row.last_trade_price;
            var last_trade_size = data.query.results.row.time;
            var change = data.query.results.row.low;

            $.each(data, function(index, value) {
                $("#stock").append('Name:'+name+ 'Symbol:' +symbol+ 'Last Trade:' +last_trade+ 'Last Trade Size:' +last_trade_size+ 'Change:'+change);
            });

    },
        error: function() {
            $("#stock").html('<p>Something has gone terribly wrong.</p>');
        }
    });

};
    //call initialize
    return {init: initialize};
}());
//call headerNav
this.getStocks = getStocks;
}).call(this);
4

1 回答 1

0

你想data.query.results.row在你的each

var symbol = ["GOOG", "AAPL", "A", "AA", "ABT"];

$.ajax({
  url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D" + symbol + "%26f%3Dnsl1d1t1c1ohgv%26e%3D.csv'%20and%20columns%3D'name%2Csymbol%2Clast_trade_price%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2'&format=json",
  dataType: 'json',
  success: function (data) {
    console.log(data);


    $.each(data.query.results.row, function (index, item) {
      $("body").append('Name:' + item.name + 'Symbol:' +item. symbol + 'Last Trade:' + item.last_trade_price + 'Last Trade Size:' + item.last_trade_size + 'Change:' + item.change+'<br><br><br>');
    });

  },
  error: function () {
    $("#stock").html('<p>Something has gone terribly wrong.</p>');
  }
});

演示:http: //jsfiddle.net/2LkLb/

我会先检查它是否data.query.results.row存在。我记得如果由于某种原因未获取数据,YQL 也会返回错误消息。

在浏览器控制台中可以检查数据对象,可能是其中的一个属性,类似于status. YQL 文档也会有所帮助

于 2013-01-14T01:56:01.603 回答