0

I am creating Spring mvc app. I am submitting JSON string to controller through AJAX. What I want is to redirect the page to different JSP page.

Right now I am returning the view from controller but instead of redirecting it is returning response to previous AJAX request.

Spring Controller

@RequestMapping("/hello")
public String hello() {
    return "powerseries";
}

Javascript/Ajax

$(document).ready(function(){   
        $('#getData').click(function(){
            var aa=JSON.stringify(answer);
            $.ajax({
    type: "POST",
    url: "hello",
    contentType: "application/json",
    dataType:'json',
    data:aa,
    cache: false,
    processData:false,
    success: function(status){
        console.log("Entered",status);
    },
    error:function(error){
        console.log("error",error);
    }
});
        });  
});  
console.dir(answer);

Browser Console

Browser Console showing ajax response having jsp page

1
  • instead of returning html from conroller return path and use window.location.href to redirect from ajax Commented Jan 6, 2018 at 12:05

2 Answers 2

1

When you are using AJAX, your MVC should return a special JSON response.

eg:

@RequestMapping("/hello")
@ResponseBody
public Map hello() {
    m.put('my_redirect', 'the new url');
    return m;
}

then handle this response in your AJAX's handler. Use javascript's window.location.href = resp.my_redirect; to go to the new url.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to redirect to other jsp page , use redirect inside controller method.

@RequestMapping("/hello")
 public String hello() {
   // return "powerseries";
   return "redirect:powerseries";
}

// Add method to controller .
@RequestMapping("/powerseries")
 public String returnPowerseries() {
  return "powerseries";
}

or just use $("html").html(response); if you want to entirely change your document html.

1 Comment

Thanks @manikantgautam . I tried using the same. but it didn't work out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.