在javascript函数中使用$ .post,无法为变量赋值?

我试图在函数中使用$ .post,得到结果,然后根据$ .post回调的结果返回函数true或false。 但是,回调似乎发生在父函数的返回事件之后。

这是当前代码,ret变量总是未定义但如果我在$ .post回调中警告它(),它会返回正确的结果;

function elementExists(key, type, path, appid, pid){ var ret; $.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){ ret = data; }); alert(ret); return ret; } 

正如您所发现的那样,post是异步完成的。 如果希望它是同步的,则需要使用ajax方法并将async参数设置为false。 但是,最好确认该post是异步的并构建您的代码,以便回调执行的操作独立于调用post的方法。 显然,你真的想做除警报以外的事情,但不知道如何重构这一点很难建议你。

编辑 :我知道你的代码正在检查是否存在某些东西,但它正在检查它是否有用。 如果我们知道目的是什么,那么可以建议如何在回调中完成该操作,以便可以重构该方法。

 function elementExists(key, type, path, appid, pid){ $.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){ alert(data); }); } 

函数(data)是一个回调(Asynchronous),你不能返回那样的值。

在调用页面之前不会调用回调函数,但是在调用$ .post后,“return ret”会立即执行

如果要将其设置为syncronous set async:false

请参阅文档http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype

问题是您的代码是异步执行的。 这就是在ret = data之前实际调用alert(ret),这在Ajax请求完成时发生。

您可以使用async选项使ajax调用同步(不推荐),或重新设计代码。