user07
user07

Reputation: 670

how to redirect to view in jquery ajax call using spring mvc

Now my ajax call:

  $.ajax({
                type: "POST",
                url: contextPath +"/action",
                cache:false,
                dataType: 'text',
                data: {Id:Id},
                success: function(Result){
                    alert("in success ***");
                    dialog.dialog("close");
                    window.location.href = Result;

                } ,
                error: function(Result){
                    alert("in error");
                    }
                });

My Controller code:

  @RequestMapping(value="/action", method=RequestMethod.POST)
  @ResponseStatus(value=HttpStatus.OK)
  public @ResponseBody ModelAndView getApplyTemplatePage(@RequestParam("Id")int cId){
      System.out.println("In apply template controller");
      System.out.println("the value of id "+cId+" hostname"+hostName+"templateName"+tempName);

      return new ModelAndView("applyTemplate");
  }

Now i want to redirect to applyTemplate.jsp page. My Requirement is using by ajax call how to redirect to another jsp page ?

Upvotes: 1

Views: 5164

Answers (1)

ahmed.hoban
ahmed.hoban

Reputation: 516

You can send a ResponseEntity with location header back in spring and redirect accordingly.

public ResponseEntity<?> getApplyTemplatePage(@RequestParam("Id") int cId, UriComponentsBuilder b) {
        UriComponents uriComponents = b.path("/applyTemplate.jsp").build();

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(uriComponents.toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.OK);

    }

and in the ajax call, you can get the location header and redirect accordingly.

success: function(data, textStatus, xhr) {
      window.location = xhr.getResponseHeader("Location");
    }

Upvotes: 1

Related Questions