Ajax中获取Json的list集合后进行遍历读取并显示的实例

对于json数据的遍历有以下两种方式

   var person = {"name": "张三", age: 23, 'gender': true};
		        var ps = [{"name": "张三", "age": 23, "gender": true},
		            {"name": "李四", "age": 24, "gender": true},
		            {"name": "王五", "age": 25, "gender": false}];
		        //获取person对象中所有的键和值
		        //for in 循环
		       for(var key in person){
		            //这样的方式获取不行。因为相当于  person."name"
		            //alert(key + ":" + person.key);
		            alert(key+":"+person[key]);
		        }
		
		       //获取ps中的所有值
		        for (var i = 0; i < ps.length; i++) {
		            var p = ps[i];
		            for(var key in p){
		                alert(key+":"+p[key]);
		            }
		        }

在这里我就使用第一种方式

步骤:

  1. 创建一个servlet,,用于将要list发送到前台页面中(这里的list我是读取数据库中的数据,Application是一个对象类,里面包含了name,mian等属性)
 @WebServlet("/getAllServlet")
public class getAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        UserDaoImpl dao = new UserDaoImpl();
        List<Application> list = dao.apply_list();
        System.out.println(list);

        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),list);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
 
  1. 在前台创建一个html文件,并通过ajax的get方法来接受servlet发送的list集合,并进行遍历读取并显示在页面上
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>显示</title>
    <script src="js/jquery-2.1.0.min.js"></script>
    <script>
        $(function () {
            $.get("getAllServlet",{},function (data) {
                var i=1;
                for(var list in data){
                    $("#"+i+"_div").html(data[list].main);
                    $("#"+i+"_span").html(data[list].name);
                    i++;
                }
            })
        })
    </script>
</head>
<body>
    <span id="1_span"></span>
    <div id="1_div">
    </div>
    <hr>
    <span id="2_span"></span>
    <div id="2_div">
    </div>
    <hr>
    <span id="3_span"></span>
    <div id="3_div">
    </div>
</body>
</html>

结果显示页面如下
Ajax中获取Json的list集合后进行遍历读取并显示的实例_第1张图片
其中我设置List集合基本内容是:
[Application{id=1, name=‘张三’, main=‘软件工程’}, Application{id=21, name=‘王五’, main=‘计算机科学与技术’}, Application{id=22, name=‘赵六’, main=‘金融学’,}]

你可能感兴趣的:(JavaWeb,Ajax/Json)