Redirecting after Ajax post

后端 未结 3 1606
自闭症患者
自闭症患者 2020-11-30 10:35

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?

window.APP_ROOT_URL = \         


        
相关标签:
3条回答
  • 2020-11-30 10:43

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

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

    And in your jQuery ajax handler

    success: function (res) {
        // check redirect
        if (res.redirect) {
            window.location.href = res.redirect_url;
        }
    }
    

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

    0 讨论(0)
  • 2020-11-30 10:54
    success: function(response){
        window.location.href = response.redirect;
    }
    

    Hope the above will help because I had the same problem

    0 讨论(0)
  • 2020-11-30 10:57

    Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.

    $('#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');
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题