我正在创建一个简单的股票代码,其中符号最终将通过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);
答案 0 :(得分: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>');
}
});
DEMO:http://jsfiddle.net/2LkLb/
我会先检查data.query.results.row
是否存在。我记得如果由于某种原因没有获取数据,YQL也会返回错误消息。
在浏览器控制台中可以检查数据对象,可能是其中具有status
之类的属性。 YQL文档也会有所帮助