2015-03-03 126 views
1

jQuery的ajax調用,查看現在我的Ajax調用:如何重定向在使用Spring MVC

$.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頁。 我的要求是通過ajax調用如何重定向到另一個jsp頁面

+0

您不能?因爲您需要編寫另一個控制器方法並返回到該方法的視圖。 – 2015-03-03 11:49:36

+0

你的概念沒有意義,ajax用於做一些事情而不加載整個頁面。但最後需要加載頁面。你爲什麼不直接讓控制器重定向?因爲你在成功中沒有做任何事情(除了警報和重定向)。 – 2015-03-03 12:02:54

回答

1

您可以在春季發送帶有位置標題的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"); 
    } 
+0

我正在使用jquery加載方法來滿足我的要求。 – user07 2015-03-03 13:53:01

+0

我有同樣的問題。我認爲我必須發送HttpStatus 302或303。你爲什麼發送200? – Argamidon 2015-04-29 14:40:59