将循环计数传递给ajax成功的anon函数

时间:2012-04-26 19:33:11

标签: javascript jquery ajax

在下面的示例中,key每次都等于d1.periods的长度。除了将key传递给data作为post变量之外,将key转换为successes匿名函数是更好的方法吗?

$.ajax({
  url: 'api/dates.json',
  dataType: 'json',
  success: function(d1){
    $('#scan-interactive').removeClass('disabled');
    for(var key in d1.periods){

      var html = "";
      html += '<tr id="'+d1.periods[key].id+'">';
      html += '<td class="month">'+d1.periods[key].month+'</td>';
      html += '<td class="week">'+d1.periods[key].week+'</td>';
      html += '<td class="days">'+d1.periods[key].days+'</td>';
      html += '<td class="dates">'+d1.periods[key].dates+'</td>';
      html += '<td class="open"></td>';
      html += '<td class="refunded"></td>';
      html += '<td class="closed"></td>';
      html += "</tr>";
      $('#scan-interactive table tbody').append(html);

      $.ajax({
        type: 'POST',
        url: 'api/count.json',
        dataType: 'json',
        data:{'created_at_min':d1.periods[key].created_at_min,'created_at_max':d1.periods[key].created_at_max},
        success: function(d2){
          $('#'+d1.periods[key].id+" .open").html(d2.open);
          $('#'+d1.periods[key].id+" .closed").html(d2.closed);
          $('#'+d1.periods[key].id+" .returns").html(d2.returns);                  
        }
      });

    }
  }
});

2 个答案:

答案 0 :(得分:4)

将其包裹在封口中:

(function(key){

  $.ajax({
    type: 'POST',
    url: 'api/count.json',
    dataType: 'json',
    data:{'created_at_min':d1.periods[key].created_at_min,'created_at_max':d1.periods[key].created_at_max},
    success: function(d2){
      $('#'+d1.periods[key].id+" .open").html(d2.open);
      $('#'+d1.periods[key].id+" .closed").html(d2.closed);
      $('#'+d1.periods[key].id+" .returns").html(d2.returns);                  
    }
  });

})(key);

答案 1 :(得分:2)

将密钥作为选项传递给ajax请求,然后使用this.nameofoption访问它。

for (var i = 0; i < 5; i++) {
    $.ajax({
        url: "/echo/html",
        method: "post",
        data: {
            html: "foo",
            delay: 1
        },
        context: {key: i},
        success: function(){
            console.log(this.key);
        }
    });
}

演示: http://jsfiddle.net/R9Ldd/2/

已更新为使用firebuglite