后端用get或者post从数据库取的数据如何打包成json:
需要下载json的jar包,这里有:http://download.csdn.net/detail/zhangy0329/607838
Connection ct = null; Statement sm = null; ResultSet rs = null; try{ Class.forName("com.mysql.jdbc.Driver"); //连接mysql数据库 ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8","用户名" , "密码"); sm = ct.createStatement(); rs = sm.executeQuery("select *from 表名"); JSONArray jsonData = JSONArray.fromObject(convertList(rs)); //先转成List格式,再转成json格式 System.out.println(jsonData.toString());
PrintWriter out = response.getWriter(); //把json数据传递到前端,记着前端用ajax接收 out.print(jsonData); } catch(Exception ex) { //error 代码 }
数据库取的数据转成List的操作函数:
private static List convertList(ResultSet rs) throws SQLException { List list = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } list.add(rowData); } return list; }
前端使用jQuery解析json:
success : function(Result) {
//Result是jsonArray字符串 $.each(eval(Result), function (index, item) { //index为序号,相对于json格式的Result而言,从0,1,2,3...到Result的长度减1,item就是每条jsonObject,
//取值就是:item.属性名,如item.name, item.id, item.number.....
}); },