我的Ajax调用在我的函数内成功运行但我无法在函数外返回结果。这是否与Ajax有关或我是如何从函数返回结果的?
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 :(得分:0)
那是因为我认为你从$ .post中的函数返回值... return语句不是从allfunction4()返回的。
您可能希望在http://api.jquery.com/jQuery.post/
上重新引用JQuery.post上的JQuery文档// 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"); });