由于大多数答案提到你做了异步调用,但那不是真正的原因。所以JavaScript是单线程的,只有在每次思考时才能完成。
所以首先你要调用你的函数,这个函数会放在执行上下文栈中。这个函数将在任何其他将被添加到堆栈的函数被执行之前执行。在这个函数中,你做了你的ajax调用,并且在成功时,成功函数将被放到执行上下文栈中。所以这个功能在naviSet
之前永远不会被调用。由于alert1是在naviSet
函数中进行的,因此它将被称为第一个。
和你的第二个问题:
从你的功能,我认为你相信,当$.ajax()
回报true
,你的Ajax调用是成功的,并pageCount
设置为数据。但事实并非如此。 $.ajax
不会返回true,而是真实值$
。它的一个函数返回对主jQuery对象的引用,所以你可以链接函数调用。
功能naviSet()
{
//you create a new var which is undefined
var pageCount;
// return $ which is a truethy in JavaScript, but it does not mean the ajax call was successful
if($.ajax({
type: "POST",
url: "http://localhost/mywebsite/wp-content/themes/twentyeleven/more-projects.php",
success:function(data)
{
// now you in the context of your success function
// and set the value of your variable to data
pageCount = data;
alert(pageCount); //alert 1
return true;
},
error:function()
{
$("#direction").html("Unable to load projects").show();
return false;
}
}))
//here you are still in the context of your naviSet function where pageCount is undefined
alert(pageCount); //alert 2
}
怎么把它ASNC呼叫kaleem .. :) – 2014-03-27 11:45:58