jquery.each usage and json
I'm having an issue jquery each. My jsp file includes the following lines:
`<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>
`
and so on. the relevant Js file includes the following relevant function:
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;
}
});
}
the relevant Json response looks like this:
{
"pleyars":[{
"id":0,
"name": "mmm",
"amount":"15"
},
{
"id":1,
"name": "mmm2",
"amount":"152"
}]
}
but the expected name change does not occur. I would really appreciate any assistance on this issue.
Thanks in advance, Lior
instead of
jQuery.each(players, function()
{ currPlayer=this;
$("#player"+currPlayer+"name").text(currPlayer.name);
})
use
$(players).each(function(index,value){
currPlayer = value;
$("#player"+currPlayer+"name").text(currPlayer.name);
});
if iam getting ur question correctly
Try:
success: function(JSONResponse) {
var players=JSONResponse.players;
jQuery.each(players, function(i,currPlayer)
{
$("#player"+currPlayer.id+"name").text(currPlayer.name);
})
Try this
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);
});
}
});
}
精彩评论