Displaying ajax results from yahoo finance using underscore.js

为君一笑 提交于 2019-12-12 05:18:48

问题


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);
    });

});

});

回答1:


See http://jsfiddle.net/mpBMK/

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.

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.



来源:https://stackoverflow.com/questions/14575323/displaying-ajax-results-from-yahoo-finance-using-underscore-js

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