これは、ボタンをクリックして時間を入力ボックスに戻す単純な AJAX と JSP (jquery なし) です。「 document.myForm.time.value=xmlhttp.responseText; 」という行を見てください。ここで、応答を取得し、結果を jsp に設定します。
<html>
<head>
<title>JSP and Servlet using AJAX</title>
<script type="text/javascript">
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
xmlhttp.open("GET","ControlServlet?gettime=gettime" ,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
</script>
</head>
<body>
<form name="myForm">
Server Time:<input type="text" name="time" />
<br />
<input type="button" onClick="ajaxFunction()" value="Click"/>
<br />
</form>
</body>
</head>
</html>
ここにサーブレットがあります:
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
if(request.getParameter("gettime")!= null && !request.getParameter("gettime").toString().equals("")){
PrintWriter out = response.getWriter();
Date df = new Date();
out.println(df.getTime());
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
doPost(request,response);
}
}
上記のコードを実行すると、次のように表示されます。
