i need to get 4 request from the server, i have stored all this 4 urls in this way. for information this is raw url (http://www.earthtools.org/timezone/40.714352/-74.0059731);
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.7143528&lan=-74.0059731',
getLondonLocalTime : 'getTime.php?lat=51.5001524&lan=-0.1262362',
getChennaiLocalTime : 'getTime.php?lat=13.060422&lan=80.249583',
getBangaloreLocalTime:'getTime.php?lat=12.9715987&lan=77.5945627'
}
this is calling my getTime.php and retrieving the result.
for that, i created this for in loop, but this prints only one time intead of 4 times? how can i make this to call 4 request ?
for(zone in nationZone ){
if (window.XMLHttpRequest){
zone=new XMLHttpRequest();
}else{
zone=new ActiveXObject("Microsoft.XMLHTTP");
}
zone.onreadystatechange=function() {
if(zone.readyState==4 && zone.status==200){
alert(zone.responseText);
}
}
zone.open("GET",nationZone[zone],true);
zone.send();
}
I do not mind using a solution that involves an additional third party library
-
1possible duplicate of Access outside variable in loop from Javascript closureFelix Kling– Felix Kling2011年11月17日 10:12:24 +00:00Commented Nov 17, 2011 at 10:12
3 Answers 3
You can try this if your using jQuery, but I doubt about it to work, because cross domain ajax is not allowed.
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.7143528&lan=-74.0059731',
getLondonLocalTime : 'getTime.php?lat=51.5001524&lan=-0.1262362',
getChennaiLocalTime : 'getTime.php?lat=13.060422&lan=80.249583',
getBangaloreLocalTime:'getTime.php?lat=12.9715987&lan=77.5945627'
}
$.each(nationZone , function(key, value){
$.get(value, function(response){
alert(response);
});
});
Comments
You are using the same name for the loop variable and the XHR. Don't do that.
EDIT: Also, this question has the jQuery tag, but you are not using jQuery. Instead of doing your own XHR stuff, use jQuery's ajax implementation through $.ajax or $.get. Also consider using JSONP, if the remote server supports it.
1 Comment
zone variable inside the if/else block is overwriting the zone from the for loop. Hence your loop only has one zone object to handle by the time it finishes the first iteration.
Use some other var name inside the function. The line :
`zone.open("GET",nationZone[zone],true);`
should say
`newZoneVariable.open("GET", nationZone[zone], true);`
where newZoneVariable is the var used inside the loop body.