java后台传递多个对象到ajax中,简单的放入,传递与遍历

其实这种方式已经很少用了,因为我们已经有很成熟的框架可以用,例如stringmvc+hibernate 它们对这些交互有一些很成熟的封装。

但是当不用框架时,有些东西还是需要知道的。

1.在后台代码中传递参数,放入流中。

@RequestMapping(value="test")
public void jjj(HttpServletResponse response,int s,int d){
    try {
        response.setCharacterEncoding("utf-8");
        PrintWriter pw=response.getWriter();
        List<Student> list=studentservice.getAllStudentByTeaId("1", 1);
        HashMap map=new HashMap();
        HashMap map1=new HashMap();
        map.put("list",list);
        map.put("count", 123);
        map.put("count1", 123);
        map.put("list1", list);
        JSONArray array=JSONArray.fromObject(map);
        pw.write(array.toString());
        pw.flush();
        pw.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

 2.在前端的获取中,需要jquery.js

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function btn(){
    $.ajax({
        url:"test",
        type:"post",
        data:{
            's':1,
            'd':2
        },
        cache:false,
        dataType:"json",
        success:function(data){
            for(var key in data){
                  alert(data[key].count);
                  alert(data[key].count1);
                     $.each(data[key].list,function(index,item){
                         $('#span').html($('#span').html()+"   学号  :   "+item.id+"  姓名 :"+item.name);
                     }); 
                  alert(data[key].list1);
                 } 

        }
    });
}
</script>
</head>
<body><span id="span"></span>
<input type="button" value="点击" onclick="btn()">
</body>
</html>

 

posted @ 2018-03-28 21:08  梦中云茵  阅读(2231)  评论(0编辑  收藏  举报