七度&光 2009-04-16 12:23 采纳率: 100%
浏览 238
已采纳

如何让 jQuery 在返回之前等待 Ajax 调用完成?

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;
            }
        }
    });
});

转载于:https://stackoverflow.com/questions/755885/how-do-i-make-jquery-wait-for-an-ajax-call-to-finish-before-it-returns

  • 写回答

5条回答 默认 最新

  • derek5. 2009-04-16 12:31
    关注

    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, 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?