在Ajax中不能直接处理List集合,需要将List集合转为Json数组进行处理。
首先是后台Servlet部分
List<RoomInfo> Pricels = new ArrayList<RoomInfo>();//RoomInfo是一个javabean对象 RoomInfo roominfo1 = new RoomInfo();//定义RoomInfo的一个对象 roominfo1.setPrice(Integer.parseInt(rs.getString("roomtype_price")));//rs为数据库查询返回的结果集 roominfo1.setBednum(Integer.parseInt(rs.getString("roomtype_bedNum"))); Pricels.add(roominfo1);//将roominfo1对象加入到List对象中 Gson gson = new Gson(); json = gson.toJson(Pricels); //将Pricels转化为Json数组 response.getWriter().print(json);
前台ajax部分
xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var returnJSONString = xmlhttp.responseText;//接受返回的Json数据 var returnJSON = JSON.parse(returnJSONString);//对Json数据进行解析 $("#roombedNum").append( //循环的想下拉框中加入房间价格 //循环遍历解析之后Json数组字符串 for (var i = 0; i < returnJSON.length; i++) { $("#roomprice").append( "<option value='"+returnJSON[i].price+"'>" + returnJSON[i].price + "</option>") } } }