Spring MVC 用ajax返回json给页面显示

来源:互联网 发布:迷你忍者mac中文版 编辑:程序博客网 时间:2024/04/28 00:38

Spring MVC 用ajax返回json给页面显示(spring 4)
1.用原生的HttpServletRequest,HttpServletResponse来写(加入谷歌的Gson.jar)
controller

@RequestMapping("/queryById4")    public void findById4(HttpServletRequest req,HttpServletResponse resp) throws IOException{//传过来的值int型是可以的        Student stu = studentService.findById(Integer.parseInt(req.getParameter("id")));        Gson gson = new Gson();        String jsonStr = gson.toJson(stu);        resp.setContentType("text/javascript");        resp.getWriter().print(jsonStr);    }

页面

<script type="text/javascript">    $(function(){        $("#login").click(function() {            $.ajax({                url : "${pageContext.request.contextPath}/student/queryById5",                type : "POST",                dataType : "json",                data : {id:1},                success : function(result) {                    //alert(result);                    $("#a1").text(result.name);                    $("#a2").text(result.id);                    $("#a3").text(result.age);                },                error:function(result){                    alert("Sorry,you are make a error!");                }            });        });    })    </script>

2.用spring Mvc 的注解@Responsebody,加入jackson的jar包
这里要特别注意,只能加
jackson-core-asl.jar
jackson-mapper.jar
否则各种报错(原因不明确)
controller

@RequestMapping("/queryById5")    @ResponseBody    public Student findById5(int id) {//传过来的值int型是可以的        Student stu = studentService.findById(id);        return stu;    }
0 0
原创粉丝点击