成功的ajax调用后,跟随链接href [英] Following link href after successful ajax call

查看:99
本文介绍了成功的ajax调用后,跟随链接href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个普通链接:

<a href="http://www.google.com" class="continue">Continue</a>

我已将点击绑定到一个事件,以发布如下的ajax请求:

I've bound the click to an event to post an ajax request like this:

$('.continue').click(function () {

    $.ajax({
        type: 'POST',
        url: '/url-to-post-to',
        data: mydata,
        contentType: 'application/json',
        error: function (err) {
            alert("error - " + err);
        },
        success: function () {
            return true;
        }
    });
});

我要实现的目标是成功时要遵循的链接....
即,如果没有错误,则应将用户重定向到google.

What I'm trying to get to happen is the link to be followed on success....
ie, if there is no error, user should be redirected to google.

我知道我可以将window.location.href放入成功处理程序中,但是我试图尽可能避免这种情况

I know I can put window.location.href in the success handler, but I was trying to avoid this if possible

推荐答案

不幸的是(在您的情况下),ajax是异步的,这意味着您的click函数会启动ajax调用,然后继续运行而不会引起任何注意(因此最后没有返回任何内容).

Unfortunately (in your case), ajax is asynchronous, meaning that your click function starts the ajax call and then continues running without paying any attention to what it does (and thus returns nothing at the end).

成功函数稍后会被调用(当ajax成功返回时),它是一个完全不同的函数,因此它返回的true与您原始的click函数无关.

The success function is called later (when the ajax returns successfully) and is a completely different function, so its returning true has no bearing on your original click function.

所有这些,您将需要使用javascript覆盖锚标记的自然行为(直接转到google.com)以及随后发生的事情(重定向).

All this to say, you will need to use javascript to override the anchor tag's natural behavior (go directly to google.com) and what happens afterward (redirect).

$('.continue').click(function (e) {
    e.preventDefault(); // otherwise, it won't wait for the ajax response
    $link = $(this); // because '$(this)' will be out of scope in your callback

    $.ajax({
        type: 'POST',
        url: '/url-to-post-to',
        data: mydata,
        contentType: 'application/json',
        error: function (err) {
            alert("error - " + err);
        },
        success: function () {
            window.location.href = $link.attr('href');
        }
    });
});

这篇关于成功的ajax调用后,跟随链接href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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