I will briefly show you how you can get a hang of it using a simple JSP file and a small piece of JavaScript (YUI). If you do not have an idea about AJAX yet, you'd probably want to read about it first before going beyond this paragraph.
An AJAX response in XML format requires writing client code to parse it into DOM model, for instance:
<bean>
<name>foo</name>
<description>foobar</description>
<id>10000</id>
</bean>
Then some annoying JSDom bits to extract the data, which I'm not going to write. As I could recall, my last time of writing AJAX and DOM stuffs was a year ago for a Java webapp which requires validating the form fields by sending synchronous request to webMethods endpoints.
This might just be another article about JSON which you have read before from other sites, yes, it is. Anyway, a response can also be sent in JSON (which is basically string then be evaluated using JavaScript eval() method), e.g.
{"name": "foo",
"description": "foobar",
"id": "10000"}
Data can then be extracted easily unlike DOM, e.g.
var jsonObj = eval("(" + responseText + ")");
var name = jsonObj.name;
Before I end this blog so that you can find out more by yourself ;-), this is the JSP used to generate the response:
<%@ pageAnd this is the HTML used to send the request and receive the response:
language="java" contentType="text/json; charset=utf-8"
import="org.json.simple.JSONObject"
%>
<% response.setContentType("text/json; charset=utf-8"); %>
<%
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", request.getParameter("name"));
jsonObj.put("description", request.getParameter("description"));
jsonObj.put("id", new Long(request.getParameter("id")));
out.print(jsonObj);
out.flush();
%>
<html>
<head>
<title>Test AJAX</title>
<script type="text/javascript" src="js/yui-2.2.2/yahoo/yahoo-min.js"></script>
<script type="text/javascript" src="js/yui-2.2.2/connection/connection-min.js"></script>
<script type="text/javascript">
function getAjaxRequest(url, callback){
return YAHOO.util.Connect.asyncRequest('POST', url, callback, "name=foo&description=foobar&amp;id=10000");
}
</script>
</head>
<body>
<script type="text/javascript">
var callback = {
success: function(o){ alert("Successful: \n" + o.responseText + "\n" + o.getAllResponseHeaders)
var jsonObj = eval("(" + o.responseText + ")");
// Some reflection here
var jsonDump = "";
for(key in jsonObj){
jsonDump += key + ": " + jsonObj[key] + "\n";
}
alert(jsonDump);
},
failure: function(o){ alert("Failed: \n" + o) },
argument: []
}
getAjaxRequest("testJsonResponse.jsp", callback);
</script>
</body>
</html>
One final and common note though, if you ever come across designing a webapp with AJAX functionality, do keep the response format consistent, i.e. use application/xml OR text/json NOT both, so that you will not confuse the developers at another end of which they should expect.
- yc, raining
No comments:
Post a Comment