小编典典

我如何通过Ajax从Spring Controller获取数据?

ajax

ajaxjsp页面上有一个通过URL调用spring控制器的页面/check

$.ajax({
    type : "GET",
    url : "${pageContext.request.contextPath}/check",
    data : {
    "id" : ${articleCount}
    },
    success: function(data){
    //response from controller
    }
});

现在,控制器看起来像

@RequestMapping("/check")
public String check(@RequestParam Integer id, HttpServletRequest request,
        HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        model.addAttribute("alreadySaved", true);
        return view;
    } else
        model.addAttribute("alreadySaved", false);

    return view;
}

我发送的数据使用模式,并试图访问它success: function(data)"${alreadySaved}",但它显示为空白。

有什么方法可以true/false在查看页面上接收该数据?


阅读 383

收藏
2020-07-26

共1个答案

小编典典

您必须为Spring Ajax调用示例添加@ResponseBody批注

@RequestMapping("/check")     
@ResponseBody
public String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        model.addAttribute("alreadySaved", true);
        return view;
    } else {
        model.addAttribute("alreadySaved", false);
        return view;
    }
}
2020-07-26