我在这里遇到了一些问题。我试图实施以下情形:
- 用户打开主页,看到其他用户的列表,点击 添加一个到他的好友列表。
- 我向服务器资源发出Ajax请求以验证用户 是否已登录,如果有,我发出另一个Ajax请求到另一台服务器 资源,以实际将其添加到用户的好友列表中。
听起来很简单吗?以下是我所做的:我创建了一个函数isLoggedIn
,它将向服务器发出第一个请求,以确定用户是否已登录。我使用jQuery.ajax
方法发出此请求。这是我的函数看起来像:
function isLoggedIn() {
$.ajax({
async: "false",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/isloggedin",
success: function(jsonData) {
alert("jsonData =" + jsonData.LoggedIn);
return jsonData.LoggedIn;
}
});
}
返回JSON是非常简单的,它看起来像如下:
{ LoggedIn: true } or { LoggedIn : false }
现在这种方法,实际工作并正确显示警告:如果登录JsonData = true
,以及JsonData = false
如果没有登录 到现在为止没有任何问题,出现问题时,我尝试调用这个方法:我把它像这样:
$(".friend_set .img").click(function() {
debugger;
if (isLoggedIn()) {
alert("alredy logged in");
trackAsync();
popupNum = 6;
}
else {
alert("not logged in"); //always displays this message.
popupNum = 1;
}
//centering with css
centerPopup(popupNum);
//load popup
loadPopup(popupNum);
return false;
});
调用isLoggedIn
总是返回false
,并返回false before the ajax request finishes (because the message
jsonData = true is displayed after the message "not logged in". I made sure that the request is **NOT** Asynchronous by stating
async:false`!
虽然它显然仍然是异步工作的。我在这里错过什么人?
不要紧'{异步:“ false“}'与'{async:false}'? – 2009-10-07 13:38:55
@Cory Larson不,没关系,事情是,该方法在ajax请求完成之前返回false。 – Galilyou 2009-10-07 13:42:50