i make a simple REST web service consumer using HTML and javascript. here’s the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp = new XMLHttpRequest(); //@slaks: i put it here
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
var empname = document.getElementById("empname");
var age = document.getElementById("age");
if (xmlhttp.readyState == 4) {
//alert(xmlhttp.status);
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
if (det.age > 0 ) {
empname.value = det.name;
age.value = det.age;
}
else {
empname.value = "";
age.value ="";
alert("Invalid Employee ID");
}
}
else
alert("Error ->" + xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<h1>Call Employee Service </h1>
<table>
<tr>
<td>Enter Employee ID : </td>
<td><input type="text" id="empno" size="10"/> <input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
<tr>
<td>Enter Name : </td>
<td><input type="text" readonly="true" id="empname" size="20"/> </td>
</tr>
<tr>
<td>Employee Age : </td>
<td><input type="text" readonly="true" id="age" size="10"/> </td>
</tr>
</table>
</body>
</html>
that code only show an employee name and age from the REST web service on the HTML textbox when a getDetail button is pressed. the parameter is employee number (empNo).
the main problem is, why this code only works once??
for example, if i put 1 on the empNo textbox and i pressed getDetail button, for the first time only, it will display the name and the age of the employee based on employee number that i was entered before. but for the second or third i press the getDetail button, it not works anymore. i’ve tried to give some alert to help me for debugging that code but the result is xmlhttp.onreadystatechange = function() only works once on the first time i pressed the getDetail button.
has anyone know how to solve this problem?? really stuck in here.. thanks a lot for helping me..
FYI: here’s my web service code:
package com.webservices.TestWS1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//@Path("/hello")
@Path("/hello/{empno}")
public class Hello {
@GET // this method process GET request from client
@Produces("application/json") // sends JSON
public String getJson( @PathParam("empno") int empno) { // empno represents the empno sent from client
switch(empno) {
case 1 :
return "{'name':'George Koch', 'age':58}";
case 2:
return "{'name':'Peter Norton', 'age':50}";
default:
return "{'name':'unknown', 'age':-1}";
} // end of switch
} // end of
}
Put this between the script tag