2017-02-15 83 views
-2

我有一种情况,我需要从ajax调用中获取值,然后将该值传递给回调函数。就像这样:传递输出作为回调的输入参数

function getValue(callback){ 
    var val = getfromajax(); 
    //need to return value and then execute the callback here 
    return val; 
    callback(); 
} 

var myval = getValue(function(){ 
    alert(myvalue) 
}) 

在上面的例子中functon showValue我需要调用的getValue和使用返回的值,并把它传递给回调函数(它提醒它)。

有没有办法做到这一点?

+1

getfromajax()*异步*顾名思义? – David

+0

是的,实际上它是ajax()函数。 – Lamar

+1

您最好阅读:[如何从异步调用返回响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call )。 'getfromajax()''' – charlietfl

回答

0

你只把它传递给回调函数作为参数

function getValue(callback){ 
    var val = getfromajax(); 

    callback(val); 
} 

var myval = getValue(function(myvalue){ 
    alert(myvalue) 
}); 

注意,如果getfromajax是异步的,这并不工作。

+0

因此,getValue必须返回语句,“var myval”实际上做了什么? – Lamar

+0

其实是这样,谢谢!顺便说一句,getfromajax是$ .ajax()调用的别名,我在.done()作用域中分配val。 – Lamar