joesid joesid - 1 month ago 9
Ajax Question

How to receive and parse a json data from jsp?

I send a json from servlet like that

User profileUser = userService.get(id);
request.setAttribute("profileUser", profileUser);
JSONObject json = new JSONObject();
try {
json.put("profileUser", profileUser);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/json");
response.getWriter().write(json.toString());


And in javascript in ajax call

$.ajax({
cache : false,
type : "GET",
url : "UserServlet?id=" + userId,
success : function(result) {
alert(result.profileUser);
}
});


The result of alert is giving me Entity.user but if I want to call result.profileUser.uuid or property of that user returns me undefined . Can anyone please help me?

Answer

If you're sending json to your Ajax client, then you need to specify that you're about to recieve json type. Like this:

$.ajax({
    cache : false,
    type : "GET",
    dataType : "json",
    url : "UserServlet?id=" + userId,
    success : function(result) {
        alert(result.profileUser);
    }
});

That will cause your success method to evaluate the result parameter as json object.