Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONArray duplicate same result [closed]

In my project, I used JSON to pass readed data from database to client side.In this code I put JSONObject in to JSONArray and pass to client side.

This my code for 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();

And this is my javascript code:

$.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
    }

});

I don't know why I take duplicate same result in alert ?

like image 386
Farshid Shekari Avatar asked Dec 15 '14 07:12

Farshid Shekari


1 Answers

Update your java code as follow:

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();
like image 113
tvahid Avatar answered Nov 12 '22 01:11

tvahid