2012-02-04 48 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