使用underscore.js显示来自Yahoo Finance的Ajax结果 [英] Displaying ajax results from yahoo finance using underscore.js
问题描述
脚本已成功检索数据,但是我无法使用underscore.js获取要显示的行"的结果.特定的故障点是"var = resultContentTemplate".无法解决这个问题.
Script is successfully retrieving data but I can not get the results of the "row" to display using underscore.js. The specific point of failure is the "var = resultContentTemplate". Can not figure this out.
$(document).ready(function(){
var symbols = symbols || ['GOOG','A','AA','AAN'];
var yqlUrl = "http://query.yahooapis.com/v1/public/yql";
var historicalUrl = 'http://finance.yahoo.com/d/quotes.csv';
var queryTemplate = _.template("select * from csv where url='" + historicalUrl + "?s=<%= symbol %>&f=n0s0l1' and columns='name,symbol,LastTradePriceOnly'");
var resultPlaceholderTemplate = _.template(
'<li id="<%= id %>">Please wait, Loading quotes...</li>');
var resultContentTemplate = _.template(
'<ul>'
+ '<li><% _.each(results, function(row) { %>'
+ '<%=row.name %>'
+ '<%=row.symbol %>'
+ '<%=row.LastTradePriceOnly %>'
+ '<% }); %>'
+ '</li>'
+ '</ul>');
// display the results of the query, replacing the 'loading' placeholder
function displayResult(id, queryResult, symbol) {
var resultsAsHtml = resultContentTemplate({results: queryResult.row, symbol: symbol});
$('#' + id).html(resultsAsHtml);
}
_.each(symbols, function(symbol) {
var resultId = _.uniqueId();
// lay down a placeholder
$('#resultContainer').append(resultPlaceholderTemplate({id:resultId, symbol:symbol}));
$.ajax({
url: yqlUrl,
data: {q: queryTemplate({symbol:symbol}), format: 'json'},
context: $('#resultContainer')
}).done(function(output) {
console.log(output);
var response = _.isString(output) ? JSON.parse(output) : output;
displayResult(resultId, response.query.results, symbol);
}).fail(function(err) {
console.log('the thing failed with an error');
console.log(err.responseText);
});
});
});
推荐答案
请参见 http://jsfiddle.net/mpBMK/
您的代码对每个符号发出一个ajax请求.因此,将为每个符号调用displayResult,而queryResult参数只有一个子级,即该符号的行.
Your code is making one ajax request per symbol. Hence, displayResult is called for each symbol, and queryResult parameter has only one child, the row for that symbol.
resultContentTemplate已经获取了单行,因此您不应该遍历结果.相反:
The resultContentTemplate already gets the single row so you shouldn't iterate over results. Instead:
var resultContentTemplate = _.template(
'<ul><li><%=result.name %><%=result.symbol %><%=result.LastTradePriceOnly %></li></ul>');
...
//in displayResult(...) which is called once per symbol
var resultsAsHtml = resultContentTemplate({result: queryResult.row, symbol: symbol});
通过提琴弄清楚问题是什么以及如何解决.
It should be clear by the fiddle what the issue was and how it can be fixed.
这篇关于使用underscore.js显示来自Yahoo Finance的Ajax结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!