2
$(document).ready(function(){
    $('#id1').click(function(){

        $.ajax({
            type:"GET",
            url:" ggs.erm.servlet.setup5.Page",
            success:function(response){
                var obj = JSON.parse(response);
                alert(obj);
            }
        });
    });
});

I am facing problem with parsing JSON object i receive from server.

Connection con = null;
JSONObject json = new JSONObject();
JSONArray jarray = new JSONArray();
try{
    con =ConnectionPool.getConnection();
    String sql = "select country from country_name";
    Statement stmt = con.createStatement();
    ResultSet rs =  stmt.executeQuery(sql);
    while(rs.next())
    {
        jarray.put(rs.getString(1));    
    }
    json.put("country", jarray);
}
catch(Exception e){e.printStackTrace();}
finally{
    try {
        con.close();
    } catch (SQLException e) {
    e.printStackTrace();}
    }
    response.setContentType("application/json");
    try {
        response.getWriter().write(json.toString());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
}

This is code for generating json.
Problem is How to parse the JSON object I get on Client Side.

4
  • What does your json string look like? what error are you getting? Commented Jan 30, 2013 at 6:37
  • 1
    You don't need to call JSON.parse as this should be done automatically if the content-type is application/json. Commented Jan 30, 2013 at 6:38
  • when i Run servlet code, I get JSON :{"country":"[\"AFGHANISTAN\",\"ALBANIA\",\"ALGERIA\",\"AMERICAN SAMOA\"]"}. on Client side : object[] {somethibg like it} pop ups in alert Box,Instead it I want What is inside JSON . Commented Jan 30, 2013 at 6:42
  • What do you get if you call alert(response)? I would expect your returned object to have a property called country which is an array of string: obj.country[]. Commented Jan 30, 2013 at 6:45

1 Answer 1

1

Don't use alert() to debug. It just gives you the toString() value, which is [object Object].

Instead, log the object to the console.

console.log(response);

// or

var obj = JSON.parse(response);
console.log(obj);

Open the developer tools in your browser to view the content of the object.

Sign up to request clarification or add additional context in comments.

1 Comment

I am working on autocompleting using ajax : so code for it is :->$("#id").autocomplete({source:var_name}); Here var_name should be a JSON string . How to put the JSON string which i get in response in var_name. Will Var var_name = response work????