2014-02-20 40 views
0

我有一个问题,此功能在不同的Javascript函数中使用jquery ajax调用?

function readComm(){ 
    $.post("something.php", {read:"read"}, function(data){ 
     retVal = $.trim(data).toString(); 
     console.log(retVal); 
     return retVal; 
    }); 
} 

应该调用PHP文件,并读取文本文件的一些价值。它是这样做的,并从功能上正确地打印在我的控制台上。问题是当我想在另一个函数中使用该值时。它说这个值是未定义的。 retVal是一个全局变量,所以这不是问题。

有没有人有一个想法可能是什么问题?

+4

'$ .post()'默认是异步的。在上面的回调中设置之前,可能你正试图使用​​'retVal'的值。 – techfoobar

+2

这看起来像另一个副本http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs

+1

哦,不再... – kapa

回答

0

如果你正在做这样的事情:

readComm(); 
alert(retVal); 

那么这是行不通的,因为readComm是一个异步函数。任何依赖于retVal的东西必须要么在该函数内部,要么被它调用,要么被充分推迟(例如,一个被异步调用添加的元素调用的函数)

1

你应该改变你的角度来使用回调函数的方法,因为你$.post做的是异步的:

function readComm(callback){ 
    $.post("something.php", {read:"read"}, function(data){ 
     retVal = $.trim(data).toString(); 
     console.log(retVal); 
     callback(retVal); 
    }); 
} 

function nextStep(retVal){ 
    alert(retVal); 
} 
readComm(nextStep); 

它做什么实际上正在使用nextStep回调函数的下一个步骤。