2011-07-23 65 views
0

我有問題每個jquery。我的JSP文件包含以下行:jquery.each用法和json

`<script type="text/javascript" src="js/monopolyAL.js"></script> 
... 
<script type="text/javascript"> 
    $(this).ready(function() { 
     // window.setTimeout(myTimerTask, 1000); // for a single timeout event 
     window.setInterval(myTimerTask, 3000); // for periodical timeout events 
     myTimerTask(); 
     }); 
</script> 

...

<table title="Player Information" id="playersDataTable"> 
       <tr> 
        <td>Player's Icon</td> 
        <td>Player's Name</td> 
        <td>Player's money</td> 
       </tr> 
       <tr> 
        <td id="player0Icon">bla</td> 
        <td id="player0name">bla</td> 
        <td id="player0money">bla</td> 
       </tr> 
` 

等。相關的js文件包括以下相關功能:

function myTimerTask() { 
     jQuery.ajax({ 
       data: "", // no data - can be ommitted 
       url: "MonopolyAjaxServlet", 
       timeout: 2000, 
       error: function() { 
        console.log("Failed to send ajax"); 
       }, 
       success: function(JSONResponse) { 
     var players=JSONResponse.players; 
     var currPlayer; 

     jQuery.each(players, function() 
     { 
      currPlayer=this; 

       $("#player"+currPlayer+"name").text(currPlayer.name); 
     }) 

      //"ver "+ver+" dice "+dice; 


       } 
     }); 
    } 

相關JSON響應看起來是這樣的:

{ 
"pleyars":[{ 
    "id":0, 
    "name": "mmm", 
    "amount":"15" 
}, 
{ 
    "id":1, 
    "name": "mmm2", 
    "amount":"152" 
}] 
} 

,但不會出現預期的名稱更改。我真的很感謝在這個問題上的任何幫助。

由於提前, 利奧爾

+1

有一個在JSON一個錯字(pleyars) – kgiannakakis

回答

1

,而不是

jQuery.each(players, function()   
{   currPlayer=this;    
$("#player"+currPlayer+"name").text(currPlayer.name);   
}) 

使用

$(players).each(function(index,value){ 
currPlayer = value; 
$("#player"+currPlayer+"name").text(currPlayer.name); 
}); 

如果IAM越來越烏爾問題正確

+1

玩家不是一個DOM元素,所以你可以在上面使用$(播放器)。每個。 – ShankarSangoli

0

嘗試:

success: function(JSONResponse) { 
    var players=JSONResponse.players; 

    jQuery.each(players, function(i,currPlayer) 
    { 
      $("#player"+currPlayer.id+"name").text(currPlayer.name); 
    }) 
+0

看起來非常像帕爾夫的答案 –

+0

在同一時間打字,但不完全。 'currPlayer' vs'curPlayer.id' – DaedalusFall

0

試試這個

function myTimerTask() { 
     jQuery.ajax({ 
       data: "", // no data - can be ommitted 
       url: "MonopolyAjaxServlet", 
       timeout: 2000, 
       error: function() { 
        console.log("Failed to send ajax"); 
       }, 
       success: function(JSONResponse) { 
        var players=JSONResponse.players; 

        jQuery.each(players, function(i, curPlayer) 
        { 
         $("#player"+curPlayer.id+"name").text(curPlayer.name); 
        }); 
       } 
     }); 
    }