在我的项目中,我使用JSON将readed数据从数据库传递到客户端。在此代码中,我将JSONObject放入JSONArray并传递给客户端。
这是JsonProcessing.java
servlet的代码:
JSONObject obj = new JSONObject();
JSONArray objarr = new JSONArray();
//read from DB
sql = "SELECT id, name FROM test";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("name");
obj.put("name", first);
obj.put("id", id);
objarr.add(obj);
System.out.print("\nobj: "+obj);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(objarr);
out.flush();
这是我的javascript代码:
$.ajax({
url : "/test/JsonProcessing",
type : "get",
data : {
id : 30
},
success : function(info) {
//alert(info.name);
console.log(info);
for (var i = 0; i < info.length; i++) {
alert(i + ": " + info[i].name + " " + info[i].id);
}
// data: return data from server
},
error : function() {
alert('Faild');
// if fails
}
});
我不知道为什么我会在警报中重复相同的结果?
答案 0 :(得分:5)
更新您的java代码,如下所示:
JSONArray objarr = new JSONArray();
//read from DB
sql = "SELECT id, name FROM test";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
JSONObject obj = new JSONObject(); // updated
// Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("name");
// Display values
System.out.print("\nID: " + id);
System.out.print(", Name: " + first);
obj.put("name", first);
obj.put("id", id);
objarr.add(obj);
System.out.print("\nobj: "+obj);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(objarr);
out.flush();