Spring MVC - redirect with jQuery

╄→гoц情女王★ 提交于 2020-01-07 03:55:27

问题


I am making an AJAX call to a controller, and I want to redirect to a new page on Success. So I have have the redirection logic within my success callback function. But it doesn't redirect to a new page instead it stays on the same page.

The intriguing thing is that a GET Request (with the form Data I just sent via POST) is made after the Ajax Callback is executed. that is, I see a GET Request in the Address Bar.

Here is my AJAX request

$.ajax({
        url: "processData",
        type: "POST",
        dataType: 'json',
        contentType:'application/json',
        async: false,
        data: JSON.stringify(req),
        success: function(result) {
            url = window.location.href;
            url = url.replace("processData", "getMoreData");
            alert(url); // correct url is printed
            window.location.replace(url);
        },
        error: function() {
            alert("--- Failure ---");
        }
    });

What's wrong in here?


回答1:


And what is wrong with

window.location.href='some url';

That is one thing. Another one - You should remove 'spring-mvc' tag from the question because it is not actually Spring-related.




回答2:


The answer posted by @Chlebik above is correct. The main issue I was facing was that both GET & POST requests were getting generated. So sometimes the GET request was going forward & the POST request was getting cancelled. Other times the reverse was happening & I was getting correct result.

All I had to do was to avoid the GET request, from the default form's Submit button, from getting generated.

Here's the code for that:

$('form').on('submit', function(e) {
    e.preventDefault();

I have taken the code fhttp://stackoverflow.com/questions/32953573/form-processing-via-ajax-avoiding-both-get-post-requests-from-getting-genera



来源:https://stackoverflow.com/questions/32945313/spring-mvc-redirect-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!