2014-08-27 113 views
0

我有这样的document.ready函数;函数涉及AJAX不返回值 - jQuery

function myfun(){ 
    var xx; 
    $.ajax({ 
     type: 'POST', 
     url: 'handler.php', 
     cache: false, 
     success: function(result) { 
      xx = result; 
     }, 
    }); 
    return xx; 
    } 


    var a; 
    a = myfun(); 
    alert(a); 

handle.php被设置为回波1234。但我得到警报“未定义”。我怎样才能解决这个问题?预计警报是“1234”(从阿贾克斯处理回复)

在此先感谢... :)

回答

1

这是异步的。使用回调:

function myfun(){ 

    return $.ajax({ 
     type: 'POST', 
     url: 'handler.php', 
     cache: false 
    }); 
} 

myfun().done(function(data){ 
    console.log(data); 
}); 

或者,如果您使用的是旧版本的jQuery无延迟对象:

function myfun(done){ 

    $.ajax({ 
     type: 'POST', 
     url: 'handler.php', 
     cache: false, 
     success: done 
    }); 
} 

myfun(function(data){ 
    console.log(data); 
}); 

https://stackoverflow.com/search?q=ajax+not+returning+data

+0

好的......问题已修复..我将此标记为已接受... – 2014-08-27 19:40:59

0

因为你返回值之前Ajax调用可以完成,阿贾克斯通话时默认是异步的,你可以在success回拨里面alert,那时你的变量将会有你设定的值:

function myfun(){ 
    var xx; 
    $.ajax({ 
     type: 'POST', 
     url: 'handler.php', 
     cache: false, 
     success: function(result) { 
     xx = result; 
     alert(xx); 
     }, 
    }); 
} 

myfun(); 
0

这是一个异步调用的问题。您可以重写代码,如:

var xx; 
    var a; 

    function myfun(){ 
    $.ajax({ 
     type: 'POST', 
     url: 'handler.php', 
     cache: false, 
     success: function(result) { 
      xx = result; 
     }, 
    }); 
    } 

myfun(); 
alert(xx);