Javascript:闭包问题,我猜..或者什么奇怪的事情?
嗯,我使用 JQuery 进行 Ajax Post 请求并获取数据。
Ajax 工作正常,但是:
coordinates = [];
$.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); alert(coordinates); }); // Alerts the Coordinates as Expected :)
但是..
$.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); });
alert(coordinates); // Alerts with a Blank Box :(
为什么会发生这种情况?
两者都应该使用相同的数据发出警报......因为坐标对于两者来说都是全局的!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这一例中:
您甚至在帖子从服务器返回之前就立即执行警报。
所以我想说这个问题更多地与执行顺序有关,而不是与闭包有关。
In this one:
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.
您的
alert(coordinates);
在function(result) {...}
调用之前执行。欢迎来到异步世界。
Your
alert(coordinates);
executes beforefunction(result) {...}
invocation.Welcome to the asynchronous world.
这是有道理的。在您的第二个示例中,
alert(coordinates);
立即发生。而coordinates = result.split(',');
发生的时间相对较晚 - 在请求成功之后。如果你想让第二个例子工作,你必须等待坐标被分配。像这样的工作小提琴:http://jsfiddle.net/UtXgK/11/
假设不需要从 $.post 返回结果的时间超过 5 秒。
It makes sense. In your second example,
alert(coordinates);
is happening right away. Whereascoordinates = 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/
Assuming it takes no longer than 5 seconds to return a result from your $.post.