Javascript: Closure Problem, I Guess.. or something strange?
Well, I was using JQuery for Ajax Post request and getting the data back.
Ajax is working fine, but:开发者_运维知识库
coordinates = [];
$.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); alert(coordinates); }); // Alerts the Coordinates as Expected :)
But..
$.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); });
alert(coordinates); // Alerts with a Blank Box :(
Why is this happening ?
Both should alert with same data.. as coordinates is global to both!In this one:
$.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); });
alert(coordinates);
You are immediately doing the alert before the post even returns from the server.
So I would say the problem has more to do with the order of execution than the closure.
Your alert(coordinates);
executes before function(result) {...}
invocation.
Welcome to the asynchronous world.
It makes sense. In your second example, alert(coordinates);
is happening right away. Whereas coordinates = result.split(',');
is happening relatively much later - after the request succeeds. If you want to make the second example work, you have to wait for the coordinates to be assigned. Something like this working fiddle:
http://jsfiddle.net/UtXgK/11/
var coordinates = 'no response from server yet';
$.post("/echo/json/",{json:'{"data":"one,two,three"}'},function(result) { coordinates=result.data.split(','); alert(coordinates[1]);});
setTimeout(function(){ alert(coordinates[2]); }, 5000);
Assuming it takes no longer than 5 seconds to return a result from your $.post.
精彩评论