AJAX in 50 simple lines: Requesting HTML and Producing JSP

First we need a simple JSP as a service.
http://localhost:8080/jsp/request.jsp?name=Chris


<%
String name = request.getParameter("name");
if ( name != null )
out.print( name.length() );
%>

The JSP simply returns the length of the string. The format is simple text, no XML.
Then we need a HTML page. It shows two text fields. One with an attached onkeyup() listener and one which displays the result, the length of the string in the first text field. The AJAX-request is inside a function called call() by the listener.


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Der Längenmann</title>
<script type="text/javascript">
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
function call()
{
var value = document.getElementById("name").value;
if ((value == null) || (value == "")) return;
var url = "/jsp/request.jsp?name=" + escape(value);
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = update;
xmlHttp.send(null);
}
function update()
{
if ( xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;
document.getElementById("length").value = response;
}
}
</script>
</head>
<body>
Nutzung online: <b>http://localhost:8080/jsp/request.jsp?name=Chris</b>.
<form>
Name: <input type="text" name="name" id="name" onKeyUp="call();" />
<br>
Length: <input type="text" name="length" id="length" />
</form>
</body>
</html>

The best solution is to use an AJAX framework like prototype, but this is only a very simple example „how this stuff works“ (is there a copyright on the sentence?)

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert