0

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!

4

3 回答 3

1

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.

于 2011-05-03T04:05:46.303 回答
1

Your alert(coordinates); executes before function(result) {...} invocation. Welcome to the asynchronous world.

于 2011-05-03T04:06:04.797 回答
0

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.

于 2011-05-03T04:06:25.900 回答