2012-03-13 68 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功能。