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

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

问题描述

我有一个服务器端的功能,需要登录。如果用户已登录该函数将返回1成功。如果不是,则该函数将返回的登录页面。

我想打电话给使用Ajax和jQuery功能。我要做的就是用普通的链接提交请求,以应用在其上点击功能。如果没有登录或者函数调用失败的用户,我想Ajax的调用返回true,这样在href触发器。

然而,当我用下面的code,函数退出Ajax调用之前完成。

我如何将用户重定向到正常的loginpage?

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

解决方案

如果您不希望$阿贾克斯()函数立即返回,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.

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

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