0

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

});

});
4

1 回答 1

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.

于 2013-01-29T04:36:44.003 回答