Blogger :
E-Surfers Weblog
All posts :
All posts by E-Surfers Weblog
Category :
XML
Blogged date : 2005 Aug 30
People all over the internet are talking about the hottest buzzword - AJAX (or Asynchronous JavaScript and XML). As we already know, it is not a technology in itself, but a term that refers to the use of a combination of technologies to create interactive web applications, including HTML (or XHTML) and CSS, DOM, the XMLHttpRequest object. Now we can see some excellent applications using AJAX such as Google Maps.
I also use it in my online exam project. The following are the code:
xmlhttp.js, which used to create the XMLHttpRequest Object
function getHTTPObject() {
var xmlhttp;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp=false
}
}
@else
xmlhttp=false
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!=`undefined`) {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false
}
}
return xmlhttp;
}
var xmlhttp = getHTTPObject();
The function below communicate with JSP and return the result of the operation
function makePaper(planid, roomid) {
var url = "makepaper.jspplanid=" + planid + "&roomid=" + roomid;
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
result = xmlhttp.responseText;
if (result == `success`) {
alert("Success!");
} else {
alert("Failed!");
}
}
}
xmlhttp.send(null);
return false;
}
The server side JSP is something like this:
<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"
%><%
String paperroomid = (String)request.getParameter("roomid");
String paperplanid = (String)request.getParameter("planid");
makepaper.setRoomid(paperroomid);
makepaper.setPlanid(paperplanid);
boolean b = makepaper.setPapers();
if (b) {%>success<%} else {%>false<%}%>
The code above works only the first time, from the second time on, the function return quickly without performing any operation. I had encounted the same issue before and I had solved it by adding an additional parameter currTime as follows:
var url = "answer.jspexamid=" + examid + "&examanswer=" + thisvalue + "&currTime=<%=new java.util.Date()%>";
This time I solve the problem by adding an additional parameter that use the javascript Date function. So, I can ensure that each time a new request is made.
function makePaper(planid, roomid) {
var now = new Date();
var url = "makepaper.jspplanid=" + planid + "&roomid=" + roomid + "&time=" + now.getTime();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
result = xmlhttp.responseText;
if (result == `success`) {
alert("Success!");
} else {
alert("Failed!");
}
}
}
xmlhttp.send(null);
return false;
}
Ok, Below are some resources about AJAX: