2012-03-13 171 views
1

我希望使用jQuery.post类来返回(不警告)函数内的响应。返回jQuery Ajax Post

下面给出具有适当值的警报:

function test_func() { 
    $.post("test.php", { cmd: "testing" }, function (data) { alert(data); }) 
} 

(显示警报以适当的值)

我尝试以下:

function test_func() { 
    return $.post("test.php", { cmd: "testing" }, function (data) { return data; }) 
} 

(返回对象)

function test_func() { 
    var tmp; 
    $.post("test.php", { cmd: "testing" }, function (data) { tmp=data; }) 
    return tmp; 
} 

(返回undefined)

var tmp; 

function setTmp(n) { 
    tmp=n; 
} 

function test_func() { 
    t=$.post("test.php", { cmd: "testing" }, function (data) { setTmp(data); }) 
} 

(返回undefined)

function test_func() { 
    t=$.post("test.php", { cmd: "testing" }) 
    return t.responseText; 
} 

(返回undefined)

所以,这是怎么回事?我怎样才能让“test_func()”返回数据响应文本?

回答

0

该协议是AJAX是异步的一个可能的解决方案是将其设置为同步像

$.ajaxSetup({ 
async:false 
}); 

然后

function test_func() { 
var temp; 
    t=$.post("test.php", { cmd: "testing" }) 
    return t.responseText; 
} 

答案只有让你的当前设置工作别人有更好的如何处理它

+0

太棒了,谢谢你的帮助。这是有启发性的。已实施,现在可以使用。 – Gaias 2012-03-13 05:19:56

1

作为异步请求,只要调用该函数,就无法获得响应。相反,您传递给$.postfunction旨在成为一个回调,只要响应完成就会执行一些操作。考虑以下几点:

function myCallback(response) { 
    // do something with `response`... 
} 

function test_func() { 
    $.post("test.php", { cmd: "testing" }, myCallback) 
} 

,而不是直接返回响应,可以改为操纵它根据需要在myCallback功能。