2013-05-29 32 views
1

我的Ajax調用在我的函數中成功運行,但是我無法將結果返回給函數外部。這與Ajax有什麼關係,或者我如何試圖從函數返回結果?Ajax post方法沒有返回函數的值

HTML

<table> 
    <tr> 
     <th> Vote </th> 
    </tr> 
    <tbody> 
    <tr class="vote"> 
     <td id="upvote">1</td> 
     <td id="downvote">-1</td> 
    </tr> 
    <tr> 
     <td id="newvote"></td> 
    </tr> 
    </tbody> 
</table> 

JQuery的

$(document).ready(function(e) { 
    var myvote = allFunction4(); //returns undefined 
    alert(myvote); 

}) 

function allFunction4() { 
    $('.vote').children().click(function() { 
     var vote = $(this).text(); 
     var timestamp = 1369705456; //value I know exits in db 
     $.post('forumvote.php', {'timestamp': timestamp, 'vote': vote}, function(result, success) { 
      var newvotes = result; 
      alert(newvotes); //this works 
      return newvotes; 
     }) 
    }) 
} 

回答

0

那是因爲我認爲你是從內.post的$函數返回值... return語句並非來自allfunction4返回( )。

你可能想在http://api.jquery.com/jQuery.post/

// Assign handlers immediately after making the request, 
// and remember the jqxhr object for this request 
var jqxhr = $.post("example.php", function() { 
alert("success"); 
}) 
.done(function() { alert("second success"); }) 
.fail(function() { alert("error"); }) 
.always(function() { alert("finished"); }); 
// perform other work here ... 
// Set another completion function for the request above 
jqxhr.always(function(){ alert("second finished"); }); 
+0

我看着再次對文檔的JQuery.post重新參考jQuery的文檔,但我只是沒有看到答案,所以我切換到$阿賈克斯並設置async:false,並且這似乎做我想要的。我不確定這是否是最好的解決方案,但在我做進一步的研究時,它現在可行。謝謝。 – user2232681

+0

@ user2232681很高興.ajax爲你工作。當我專注於使用.post和您遇到的問題時,我甚至沒有想到使用.ajax--理論上它們都會產生相同的結果,實際上,使用.ajax會給您一點點控制它。在JQuery上進行討論可能會幫助你更好地理解差異 - http://forum.jquery.com/topic/what-should-i-use-post-vs-ajax – smallworld