2012-02-04 66 views
0

循环有效。但标题的更新没有。被注释掉的警报确实表明数据是正确的。jQuery .each()AJAX

<script> 
    var usercount = 0; 
    var nbw = ''; 
    var _$this = ''; 
    $('.alphabet').each(function() { 
     _$this = $(this); 
     nbw = $(this).val(); 
     $.ajax({ 
      type: "Get", 
      url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json", 
      data: "nbw=" + nbw, 
      datatype: "html", 
      success: function (response) { 
       usercount = parseInt(response.substring(0, 10)); 
       //$(_$this.target).attr('title', usercount); 
      }, 
      error: function (xhr, textStatus, errorThrown) { 
       alert('errorThrown'); 
      } 
     }); 
     $(_$this.target).attr('title', usercount); 
     //alert(nbw + ' usercount=' + usercount); 
    }); 
</script> 
+4

你射击(大概)一次26 HTTP请求?这听起来不是一个好主意。 – 2012-02-04 21:02:29

+0

'$(_ $ this.target)'是错误的。 '_ $ this'是'$(this)',$(this)没有'target'。只有'event.target'。不过我认为你也应该改变它:'_ $ this.attr('title',usercount);' – noob 2012-02-04 21:07:43

+0

我可以用字母计数返回查询。我只是不善于处理JSON回报。 – user990016 2012-02-04 21:12:24

回答

1

Ajax异步,这意味着数据会在任意时刻在未来

你必须使用你的回调内部的服务器获得了数据恢复。

代码(有几个修补程序):

<script> 
$('.alphabet').each(function() { 
    var $this = $(this); 
    var nbw = $this.val(); 
    var usercount = 0; 
    $.ajax({ 
     type: "Get", 
     url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json", 
     data: "nbw=" + nbw, 
     datatype: "html", 
     success: function (response) { 
      usercount = parseInt(response.substring(0, 10)); 
      $this.attr('title', usercount); 
     }, 
     error: function (xhr, textStatus, errorThrown) { 
      alert('errorThrown'); 
     } 
    }); 
}); 
</script> 
+0

@downvoter。我可以收到评论吗? – gdoron 2012-02-04 21:07:08

+0

我初步获得了成功的更新:回电。 – user990016 2012-02-04 21:07:17

+1

+1。这似乎是最合理的答案。问题是,为什么OP会评论这种相同的逻辑。 – davidethell 2012-02-04 21:09:01