且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何让我的jQuery等Ajax调用完成返回前?

更新时间:2023-11-20 23:32:58

如果您不希望$阿贾克斯()函数立即返回,async选项设置为false:

  $(。my_link)。点击(
    功能(){
    $阿贾克斯({
        网址:$(本).attr(HREF),
        键入:GET,
        异步:假的,
        缓存:假的,
        超时:30000,
        错误:函数(){
            返回true;
        },
        成功:函数(MSG){
            如果(parseFloat(MSG)){
                返回false;
            } 其他 {
                返回true;
            }
        }
    });
});
 

不过,我要指出,这将是反阿贾克斯的点也和你应该处理的错误和成功职能的响应。当从服务器接收到响应这些功能将仅被调用。

I have a server side function that requires login. If the user is logged in the function will return 1 on success. If not, the function will return the login-page.

I want to call the function using Ajax and jQuery. What I do is submit the request with an ordinary link, with a click-function applied on it. If the user is not logged in or the function fails, I want the Ajax-call to return true, so that the href triggers.

However, when I use the following code, the function exits before the Ajax call is done.

How can I redirect the user gracefully to the loginpage?

$(".my_link").click(
    function(){
    $.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        cache: false,
        timeout: 30000,
        error: function(){
            return true;
        },
        success: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});

If you don't want the $.ajax() function to return immediately, set the async option to false:

$(".my_link").click(
    function(){
    $.ajax({
        url: $(this).attr('href'),
        type: 'GET',
        async: false,
        cache: false,
        timeout: 30000,
        error: function(){
            return true;
        },
        success: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});

But, I would note that this would be counter to the point of ajax also, and you should be handling the response in the error and success functions. Those functions will only be called when the response is received from the server.