$ .ajax({async:false})请求仍然是异步触发?

Gal*_*you 33 ajax asp.net-mvc jquery

我这里有点问题.我正在尝试实现以下方案:

  1. 用户打开主页并查看其他用户的列表并单击以将其添加到他的朋友列表中.
  2. 我向服务器资源发出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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

返回的JSON非常简单,如下所示:

{ LoggedIn: true } or { LoggedIn : false } 
Run Code Online (Sandbox Code Playgroud)

现在这个方法实际上正常工作并正确显示警报: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;

});
Run Code Online (Sandbox Code Playgroud)

调用isLoggedInalways返回false,并返回false before the ajax request finishes (because the messagejsonData = true is displayed after the message "not logged in". I made sure that the request is **NOT** Asynchronous by statingasync:false`!

显然,它仍然是异步工作的.我在这里想念的是什么?

Roa*_*rth 62

你需要async:false,没有async:"false".(即传递布尔值false,而不是字符串"false").

编辑:同样使用异步请求,您需要在调用返回值ajax,而不是在成功处理程序内部:

function isLoggedIn() {
    var isLoggedIn;
    $.ajax({
        async: false,
        // ...
        success: function(jsonData) {
            isLoggedIn = jsonData.LoggedIn
        }
    });
    return isLoggedIn 
}
Run Code Online (Sandbox Code Playgroud)

  • 成功处理程序执行后的返回值! (4认同)