我如何一次循环100?

时间:2017-08-22 20:57:42

标签: javascript jquery

Google api只允许我一次获得100个符号。如何循环它以使其获得100个符号然后接下来的100个符号,而不是为每100个股票创建一个新脚本?或者,有更好的方法吗?

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>

        $.getJSON('https://www..com/api/public/user/token/exchange_stocks/NYSE', function(data) {

            var stocks = "";
            for (var n = 0; n < 250; n++)

            {
                console.log(data[n]["symbol"]);
                stocks += (data[n]["symbol"] +",");
                stocks = stocks.replace(/[.]/g, "");

            }



            var temp = [];
            $(document).ready(function(){
                stockInformation();
                setInterval(stockInformation, 5000);
            });
            function stockInformation()

            {

                $.ajax({
                    url:"http://finance.google.com/finance/info?client=ig&q=NYSE:" + stocks,
                    dataType:"jsonp",
                    jsonp:"callback",
                    jsonpCallback:"quote"
                });
                var i = 0; var j = 0;var status = "";
                quote = function(data){
                    var output = "<table>"
                    $.each(data, function(key, value){
                        if (value.l_cur > temp[j])
                            status = "<td style=color:green>Up</td>";
                        else if (value.l_cur < temp[j])
                            status = "<td style=color:red>Down</td>";
                        else
                            status = "<td>Same</td>";
                        j++;
                        output += "<tr><td>" + value.t + "</td><td>" + value.l_cur + "</td><td>" + value.c + "</td><td>" + value.cp + "</td>" + status + "</tr>";
                        temp[i] = value.l_cur;i++;
                    })
                    output += "</table>";
                    $("#result").html(output);
                }
            }

        });

    </script>


<div id="container">
    <div id="result"></div>
</div>

2 个答案:

答案 0 :(得分:0)

我建议您将您的股票名称划分为100个块,发出partitions.length个请求,并使用$.when等待所有请求完成。这是一个未经测试的例子:

$.getJSON('https://www..com/api/public/user/token/exchange_stocks/NYSE').then(function(data) {
  var partitions = [];
  var stocks = "";
  for (var n = 0; n < 250; n++) {
      // if n is divisible by 100, push current stocks into partition
      // and empty stocks string
      if (n % 100 === 0) {
         partitions.push(stocks)
         stocks = ""
         continue
      }
      console.log(data[n]["symbol"]);
      stocks += (data[n]["symbol"] +",");
      stocks = stocks.replace(/[.]/g, "");
  }

  // make all requests and store their $.Deferred in an array
  var requests = partitions.map(function(stockSymbols) {
     return $.getJSON("http://finance.google.com/finance/info?client=ig&q=NYSE:" + stockSymbols);
  });

  // wait for all requests to complete
  $.when.apply($, requests)
   .done(function() {
      var allStockData = [];
      for (var i = 0; i < arguments.length; i++) {
          // each argument to the done callback is a response 
          // formatted: [ data, statusText, jqXHR ]
          // concat the data to our collection of responses
          allStockData = allStockData.concat(arguments[i][0])
      }
      // do your table stuff with allStockData here
   })
})

答案 1 :(得分:0)

我在考虑以下内容。这是完全未经测试的,但至少可能会给你一些想法。

$.getJSON('https://www..com/api/public/user/token/exchange_stocks/NYSE', function(data) {
  var temp = [];
  var sympols = {};
  //get an array of all the symbols, removing the periods
  var stocks = $.map(data, function(stock){
    return stock.symbol.replace(/[.]/g, "");
  });

  //if there are more than 250, get just the first 250
  if (stocks.length > 250) stocks = stocks.slice(0, 250);

  //preload the symbols map
  $.each(stocks, function(stock){
    //default prices to 0
    symbols[stock] = 0;
  });

  //join them into a comma separated string
  stocks = stocks.join(',');

  (function updateShortList(shortlist){
    if (shortlist.length > 100) {
      //send just the first 100
      var $deferred = stockInformation(shortlist.slice(0, 100));
      //repeat function without the stocks previously processed
      $deferred.then(function(){ updateShortList(shortlist.slice(100)); });
    } else {
      //send them all
      var $deferred = stockInformation(shortlist);
      //wait 5 seconds before starting over
      $deferred.then(function(){
        //after 5 seconds, build the results, and send all the stocks again
        setTimeout(function(){
          //put all the accumulated results to the page
          $("#result").html('<table>'+ temp.join('') +'</table>');
          //clear the results
          temp = [];
          //start over
          updateShortList(stocks);
        }, 5000);
      });
    }
  })(stocks);

  function stockInformation(stocks) {
    var quote = function(data) {
      var status = "";
      var output = "";

      $.each(data, function(key, value) {
        //compare old ticker value to new ticker value
        if (value.l_cur > symbols[value.t])
          status = "<td style=color:green>Up</td>";
        else if (value.l_cur < symbols[value.t])
          status = "<td style=color:red>Down</td>";
        else
          status = "<td>Same</td>";
        //update the stored ticker value
        symbols[value.t] = value.l_cur;
        //add the row to the results collection
        temp.push("<tr><td>" + value.t + "</td><td>" + value.l_cur + "</td><td>" + value.c + "</td><td>" + value.cp + "</td>" + status + "</tr>");
      });
    }

    return $.ajax({
      url: "http://finance.google.com/finance/info?client=ig&q=NYSE:" + stocks,
      dataType: "jsonp",
      jsonp: "callback",
      jsonpCallback: "quote"
    });
  }

});