Reputation: 1529
I'm trying to retrieve JSON data from servlet and display in html. I was able to connect to servlet using jQuery .ajax() but couldn't retrieve the json value.
Below is my html sample
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="javascript/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// click function
$('#btn').click(function(){
// get the request
/*
$.ajax({url:'JsonCreationOfUrlAndContent',
type:"GET",
dataType:"json",
asyn:true,
success:function(data)
{
$("div#main").text(data.Trends[1].title);}
});
*/
//now using getJSON
$.getJSON('JsonCreationOfUrlAndContent',function(data)
{
$("div#main").html(data.Trends[1].title);
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input id="btn" type="button" name="test" value="PressME"></input>
<div id="main">
</div>
</body>
</html>
And below is my java code where i'm creating some sample JSON of structure like below
{"Trends":[
{"url":"http://google.com",
"title":"No#1 Search Engine"},
{"url":"http://bing.com",
"title":"Best socal search engine"},
{"url":"http://altavista.com",
"title":"Oldest search engine"}]}
And below is my java code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter pw =(PrintWriter)response.getWriter();
// create the JSONObject
JSONObject jobj1 = new JSONObject();
jobj1.put("url","http://google.com");
jobj1.put("title","No#1 Search Engine");
JSONObject jobj2 = new JSONObject();
jobj2.put("url","http://bing.com");
jobj2.put("title","Best socal search engine");
JSONObject jobj3 = new JSONObject();
jobj3.put("url","http://altavista.com");
jobj3.put("title","Oldest search engine");
JSONArray jarr = new JSONArray();
jarr.add(jobj1);
jarr.add(jobj2);
jarr.add(jobj3);
// now add JSONArrayO to JSONObject
JSONObject fObj = new JSONObject();
fObj.put("Trends",jarr);
pw.println(fObj);
}
Upvotes: 0
Views: 913
Reputation: 7639
Have you checked if you actually receive the json response using firebug?
I assume your commented code is the working version. In the lines you commented, there is this line:
$("div#main").text(data.Trends[1].title);
But in the one not commented, the line is a bit different:
$("div#main").html(data.Trends[1].title);
Maybe this is the cause?
Upvotes: 1