Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:我想是闭包问题吧。。还是什么奇怪的事?_Javascript_Jquery_Serverside Javascript - Fatal编程技术网

Javascript:我想是闭包问题吧。。还是什么奇怪的事?

Javascript:我想是闭包问题吧。。还是什么奇怪的事?,javascript,jquery,serverside-javascript,Javascript,Jquery,Serverside Javascript,我使用JQuery处理Ajax Post请求并获取数据 Ajax工作正常,但是: coordinates = []; $.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); alert(coordinates); }); // Alerts the Coordinates as Expected :) 但是 为什么会发生这种情况? 两者应使用相同的数据发出警报。。因为坐标

我使用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); 
在post从服务器返回之前,您将立即执行警报

因此,我想说问题更多地与执行顺序有关,而不是闭包。

您的
警报(坐标)在调用
函数(结果){…}
之前执行。
欢迎来到异步世界。

这很有意义。在第二个示例中,
alert(坐标)正在立即发生。而
coordinates=result.split(',')发生的时间相对较晚-在请求成功之后。如果要使第二个示例正常工作,必须等待分配坐标。类似这样的工作小提琴:


假设从$.post返回结果所需时间不超过5秒。

Ok。。我正在尝试一种不同的方法,但“异步世界”行非常棒!我们可以用jquery解决一些问题吗??就像我们有$(document).ready(function(){/*Stuff here*/});那么,我们可以用类似的方式来做吗。。。我们可以为这个ajax调用准备一个函数吗???您的方法显示了一个错误:setTimeout('alert(coordinates);',5000);错误:未定义坐标!!我认为现在是闭包问题??不,这不是闭包问题,您可能没有声明坐标(我的代码只是一个片段)。是的,jQuery1.5引入了链接其他事件处理程序。请参阅Promise和Deferred object文档:我已经声明了坐标(已确认),但其显示错误。你能不能给我一个jquery解决方案的片段,因为我正在研究这个问题,但我只是一个初学者!请不要介意。。我是新手!我用工作代码和你可以自己玩的小提琴编辑了我的文章。玩得开心。我们可以用jquery解决一些问题吗??就像我们有$(document).ready(function(){/*Stuff here*/});那么,我们可以用类似的方式来做吗。。。我们可以为这个ajax调用准备一个函数吗???
$.post("ajax_markers.php",{time:time},function(result) { coordinates=result.split(','); });
alert(coordinates); 
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);