Reputation: 431
i have a jsp on a server that returns me a JSON like this: {"link":"LINK_TEST","title":"TITLE_TEST"}
I am trying to get this data from a client html page but i can do it.
this is the jsp code:
<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONObject"%>
<%
JSONObject json = new JSONObject();
json.put("title", "TITLE_TEST");
json.put("link", "LINK_TEST");
out.print(json);
out.flush();
%>
The jsp looks like this: {"link":"LINK_TEST","title":"TITLE_TEST"}
And this is the client side code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.ajax({
url : 'http://my_ip:my_port/json.jsp',
data : { search: 'test' },
dataType: 'json',
success : function(json) {
var ob = jQuery.parseJSON(json);
alert(ob.link+" "+ob.title);
document.getElementById("uno").innerHTML = ob.link;
document.getElementById("dos").innerHTML = ob.title;
}
});
</script>
</head>
<body>
<h1 id="uno"></h1>
<h1 id="dos"></h1>
</body>
</html>
Upvotes: 0
Views: 1996
Reputation: 2246
Put it inside document.ready it will work and comment out datatype . i..e,
<pre>
<script>
$(document ).ready(function() {
$.ajax({
url : 'http://localhost:8080/json.jsp',
data : { search: 'test' },
success : function(json) {
var ob = jQuery.parseJSON(json);
alert(ob.link+" "+ob.title);
document.getElementById("uno").innerHTML = ob.link;
document.getElementById("dos").innerHTML = ob.title;
}
});
});
</script>
</pre>
Upvotes: 1
Reputation: 2069
Try this
//start ajax request
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
for (var i=0;i<json.length;++i)
{
$('#results').append('<div class="name">'+json[i].name+'</>');
}
}
});
Upvotes: 0