代码改变世界

SpringMVC 中getJSON的使用案例

2015-12-06 11:37  小兵故事  阅读(692)  评论(0编辑  收藏  举报


controller 返回json数据

@ResponseBody

    //查看用户信息 ?json
    @RequestMapping(value="/{username}",method=RequestMethod.GET)
    @ResponseBody //直接返回response里的io流数据,不需要加载视图
    public Map<String, User> view(@PathVariable String username){
//        return userList.get(username);
        return userList;
    }

 

jsp页面获取值:

$.each()的使用是难点

 

<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery-1.11.3.min.js">    
</script>
<script type="text/javascript">
    $(function(){
        alert(1);
        $.getJSON("/SpringMVC-C02_05/user/hhhh/zs",function(data){
            alert(data);
            $.each(data,function(key,val){
                $("#div").append("<span>"+val.userName+"</span><br/>");
            });
        });
    });
</script>
<body>
<div id="div" style="width:200px;height:200px;border:1px solid red"></div>
</body>
</html>