2017-08-18 30 views
1

正如標題所說,我想從一個控制器傳遞一個變量到一個成功的ajax調用函數,但這有可能嗎?例如:Java控制器是否可以將屬性傳遞給成功的Ajax調用?

我有這樣的控制器的Java類:

@RequestMapping(value = "checkFruit", method = RequestMethod.POST) 
@ResponseBody 
public ModelAndView checkFruit(HttpServletRequest request, String fruitInput) { 

    ModelAndView modelAndView = new ModelAndView(); 

    if (fruitInput.equals("apple")) { 
     modelAndView.addObject("fruitType", 1); //This is what I want to pass to the success ajax call. 
    } else if (fruitInput.equals("orange") { 
     modelAndView.addObject("fruitType", 2); //This is what I want to pass to the success ajax call. 
    } 

    modelAndView.setViewName("fruitGarden"); 
    return modelAndView; 
} 

並與一個AJAX調用這樣一個jsp視圖:

$("#checkFruitBtn").click(function() { 
    var fruitInput = $("input[name=fruitInput]").val(); 
    $.ajax({ 
     type: 'POST', 
     url: 'checkFruit', 
     data: 'fruitInput=' + fruitInput, 
     success: function() { 
      var fruitType= ${fruitType}; //I want to get the attribule of that "fruitType" variable set in the controller. But this is where things went wrong. 
      if (fruitType == 1) { 
       alert("This is an apple."); 
      } else if (fruitType == 2) { 
       alert("This is an orange."); 
      } 
      window.location.href = "/someURL"; 
     } 
    }); 
}); 

在上面的例子。當我點擊「checkFruitBtn」按鈕時,它會向控制器「checkFruit」發送一個ajax調用。在這個控制器中,我將設置一個變量「fruitType」,將其發送給成功的ajax調用函數。在這個成功的ajax調用函數中,我會得到「fruitType」變量的值來檢查它並根據它的值顯示警報消息......但是,事情並沒有按計劃進行。

我的問題是,有沒有一種可能的方法來獲取該「fruitType」變量的值?我已經搜索了一種方法,但仍然找不到適合我的情況。如果之前有人問過這個問題,我非常抱歉。

在此先感謝!

回答

0

With annotation @ResponseBody,Springmvc通過使用HttpMessageConverter將返回的對象轉換爲響應正文。

ModelAndView通常涉及命令對象和視圖名稱。

因此,您可以使用帶有Jsp頁面的ModelAndView,然後使用el來評估命令對象值。要使用@ResponseBody,Springmvc只返回字符串。

0
$.ajax({ 
       type: 'POST', 
       url: password_url, 
       data: '', 
       dataType: 'json', 
       success: function(response){ 

       var g = response; 
       var x= g.fruitType; //Now you can do the operation based on the output. 
相關問題