正如标题所说,我想将变量从 Controller 传递到成功的 ajax 调用函数,但这可能吗?例如:

我有一个带有 Controller 的 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 View ,如下所示:

$("#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”时,它将向 Controller “checkFruit”发送 ajax 调用。在此 Controller 中,我将设置一个变量“fruitType”以将其发送到成功的 ajax 调用函数。在此成功的 ajax 调用函数中,我将获取“fruitType”变量的值来检查它并根据其值显示警报消息...但是,事情并没有按计划进行。

我的问题是,是否有可能获取“fruitType”变量的值?我已经寻找了一种获取方法,但仍然找不到适合我的情况的方法。如果之前有人问过这个问题,我感到非常抱歉。

提前致谢!

请您参考如下方法:

通过注解@ResponseBody,Springmvc使用HttpMessageConverter将返回的对象转换为响应体。

ModelAndView通常涉及命令对象和 View 名称。

因此您可以将 ModelAndView 与 Jsp 页面一起使用,然后使用 el 来评估命令对象值。使用@ResponseBody,Springmvc仅返回字符串。


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!