Reputation: 1
I am trying to get a piece of data from server using JSP technology. I am using JSON object to do so. On client side i am using XMLHttpRequest to get the data.
To check whether it works properly, i wrote a piece of code as follow:
<head>
<script type="text/javascript">
function test(data) {
if(data){
var jsonObj= eval('(' + data + ')');
var Question= jsonObj.Question;
document.write(Question);
}
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseText != null && this.responseText)
// success!
test(this.responseText);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
function xyz(){
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("POST", "fetch.jsp", true);
client.send();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br><br><input id="Q" type="button" onclick="xyz()" >
</body>
on server side i did as follow:
<%@page import="net.sf.json.JSONObject"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% JSONObject jsonObj= new JSONObject();
jsonObj.put("Question","What is your name?");
jsonObj.put("Opt1","ji");
jsonObj.put("Opt2","ji");
jsonObj.put("opt3","ma");
jsonObj.put("opt4","sa");
String str= jsonObj.toString();
response.setContentType("text/plain");
response.getWriter().write(str);
%>
Unfortunately i am not able to get the response.
Upvotes: 0
Views: 2734
Reputation: 14463
You need to write with content type application/json.
Also don't use eval in test function.
When the data is json the test function can access the data as the json object!
In the event of parsing a string use.
JSON.parse(string).
But don't use eval
Upvotes: 0
Reputation: 943981
You are writing your JSON into the body of an HTML document, and then sending the HTML document as the response.
Don't do that. The response should be just the JSON.
Upvotes: 1