简体   繁体   中英

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 ?

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");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM