jQuery 在 Ajax 发布后重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18118627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:03:25  来源:igfitidea点击:

Redirecting after Ajax post

ajaxjquery

提问by Alain Goldman

I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?

我希望在 ajax 帖子上的成功转到主页。出于某种原因,我一直在做错。知道我应该怎么做才能解决这个问题吗?

window.APP_ROOT_URL = "<%= root_url %>";

Ajax

阿贾克斯

$.ajax({ url: '#{addbank_bankaccts_path}',
 type: 'POST',
 beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
 dataType: "json",
 data: 'some_uri=' + response.data.uri ,
 success: function(APP_ROOT_URL) {
      window.location.assign(APP_ROOT_URL);
  }
});

回答by backtrack

success: function(response){
    window.location.href = response.redirect;
}

Hope the above will help because I had the same problem

希望以上内容会有所帮助,因为我遇到了同样的问题

回答by Madan Sapkota

You can return the JSON from server with redirect status and redirect URL.

您可以使用重定向状态和重定向 URL 从服务器返回 JSON。

{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}

And in your jQuery ajax handler

在你的 jQuery ajax 处理程序中

success: function (response) {
    // redirect must be defined and must be true
    if (response.redirect !== undefined && response.redirect) {
        window.location.href = response.redirect_url;
    }
}

Note you must set dataType: 'json'in ajax config. Hope this is helpful. Thanks!

请注意,您必须dataType: 'json'在 ajax 配置中进行设置。希望这是有帮助的。谢谢!

回答by kimbaudi

Not sure why, but window.location.hrefdid not work for me. I ended up using window.location.replaceinstead, which actually worked.

不知道为什么,但window.location.href对我不起作用。我最终window.location.replace改用了,这确实有效。

$('#checkout').click(function (e) {
    e.preventDefault();
    $.ajax('/post/url', {
        type: 'post',
        dataType: 'json'
    })
    .done(function (data) {
        if (data.cartCount === 0) {
            alert('There are no items in cart to checkout');
        }
        else {
            window.location.replace('/Checkout/AddressAndPayment');
        }
    });
});