脚本成功检索数据但我无法使用underscore.js显示“行”的结果。失败的具体点是“var = resultContentTemplate”。无法理解这一点。
$(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);
});
});
});
答案 0 :(得分:1)
您的代码每个符号发出一个ajax请求。因此,为每个符号调用displayResult,而queryResult参数只有一个子节点,即该符号的行。
resultContentTemplate已经获得单行,因此您不应该迭代结果。代替:
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});
小提琴应该清楚问题是什么以及如何修复它。