在Ajax发布后重定向

Ala*_*man 11 ajax jquery

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

window.APP_ROOT_URL = "<%= root_url %>";
Run Code Online (Sandbox Code Playgroud)

阿贾克斯

$.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);
  }
});
Run Code Online (Sandbox Code Playgroud)

bac*_*ack 19

success: function(response){
    window.location.href = response.redirect;
}
Run Code Online (Sandbox Code Playgroud)

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

  • (-1)因为`assign`是有效的,并且没有JSON格式的指示(例如重定向属性). (2认同)
  • 尊敬的投票者,请发表评论 (2认同)

Mad*_*ota 8

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

{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}
Run Code Online (Sandbox Code Playgroud)

在你的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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


kim*_*udi 6

不知道为什么,但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');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)