2010-04-25 78 views
3

編輯: 這就是我需要:如何在變量中返回帖子的回覆? jQuery的

sendpost = function(a,b,c){ 
    return jQuery.post('inc/operations.php', {a:b}, c, "json"); 
}, 

rotate = function(callback){ 
    //.... 
    alert(callback); 
} 

sendpost('operation', 'test', rotate) 

舊文章: 我用這個函數返回崗位的響應:

$.sendpost = function(){ 
    return jQuery.post('inc/operations.php', {'operation':'test'}, "json"); 
}, 

我想做出點像這樣:

in:

$.another = function(){ 
    var sendpost = $.sendpost(); 
    alert(sendpost); 
} 

,但我得到:[object XMLHttpRequest]

如果我打印的物體:

jQuery.each(sendpost, function(i, val) { 
    $(".displaydetails").append(i + " => " + val + "<br/>"); 
}); 

我得到:

details abort => function() { x && h.call(x); g("abort"); } 
dispatchEvent => function dispatchEvent() { [native code] } 
removeEventListener => function removeEventListener() { [native code] } 
open => function open() { [native code] } 
setRequestHeader => function setRequestHeader() { [native code] } 
onreadystatechange => [xpconnect wrapped nsIDOMEventListener] 
send => function send() { [native code] } 
readyState => 4 
status => 200 
getResponseHeader => function getResponseHeader() { [native code] } 
responseText => mdaaa from php 

如何只返回變量中的反應呢?

+0

爲什麼地球上,你把所有的功能'$'裏面? – SLaks 2010-04-25 15:50:43

+0

如果沒有我得到:$。functionname不是函數 – robertdd 2010-04-25 15:55:39

+1

*哭*。 $是jQuery對象。如果你通常定義函數('function bar(){alert('Foo');}'),你不用'$ .bar()'調用函數,它只是'bar()'; – Matt 2010-04-25 16:01:23

回答

4

這是不可能的。

AJAX調用是異步的,這意味着您的代碼在服務器發送回覆之前繼續運行。

執行return語句時,服務器尚未回覆。

可以進行同步AJAX調用,但它會完全凍結瀏覽器,應該不惜一切代價避免。

相反,你應該讓你的函數進行一個回調,它將接收服務器的響應,並從$.post的回調中調用回調函數。 (這是jQuery的AJAX功能如何返回值)

編輯:例如:

$.sendpost = function(callback) { 
    return jQuery.post('inc/operations.php', {'operation':'test'}, callback, "json"); 
}; 

$.another = function() { 
    $.sendpost(function(response) { 
     alert(response); 
    }); 
}; 
+0

我怎樣才能回調服務器的迴應? 可以發表一個小例子嗎?謝謝! – robertdd 2010-04-25 14:52:51

+0

我在螢火蟲中收到這個錯誤:'e.success.call不是函數' – robertdd 2010-04-25 15:07:39

+0

你究竟寫了什麼? – SLaks 2010-04-25 15:16:43