如何让 jQuery 在返回之前等待 Ajax 调用完成? [英] How do I make jQuery wait for an Ajax call to finish before it returns?

查看:27
本文介绍了如何让 jQuery 在返回之前等待 Ajax 调用完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要登录的服务器端功能.如果用户登录,该函数将在成功时返回 1.如果没有,该函数将返回登录页面.

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.

我想使用 Ajax 和 jQuery 调用该函数.我所做的是使用普通链接提交请求,并在其上应用点击功能.如果用户未登录或函数失败,我希望 Ajax 调用返回 true,以便触发 href.

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.

但是,当我使用以下代码时,该函数在 Ajax 调用完成之前就退出了.

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

推荐答案

如果不希望 $.ajax() 函数立即返回,请设置 async> false 的选项:

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,
        fail: function(){
            return true;
        },
        done: function(msg){ 
            if (parseFloat(msg)){
                return false;
            } else {
                return true;
            }
        }
    });
});

但是,我会注意到这与 AJAX 的观点背道而驰.此外,您应该在 faildone 函数中处理响应.只有在收到来自服务器的响应时才会调用这些函数.

But, I would note that this would be counter to the point of AJAX. Also, you should be handling the response in the fail and done functions. Those functions will only be called when the response is received from the server.

这篇关于如何让 jQuery 在返回之前等待 Ajax 调用完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆