如何在jqueryajax调用中使用springmvc重定向到视图

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

本文关键字:springmvc 重定向 视图 jqueryajax 调用      更新时间:2023-09-26

现在我的ajax调用:

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

我的控制器代码:

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

现在我想重定向到applyTemplate.jsp页面。My Requirement正在通过ajax调用使用如何重定向到另一个jsp页面

您可以在spring中发送一个带有位置标头的ResponseEntity,并相应地重定向。

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

在ajax调用中,您可以获得位置标头并相应地重定向。

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