下面的例子将为您演示当用户在输入框中键入字符时,网页如何与 web 服务器进行通信。
本示例包括2个文件。分别为showhint.html和ShowHintServlet。
以下是详细代码:
showhint.html
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-
<html>
-
<head>
-
<title>showhint.html</title>
-
-
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
-
<meta http-equiv="description" content="this is my page">
-
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-
-
-
<script language="javascript" type="text/javascript">
-
var xmlHttp;
-
function createXMLHttpRequest(){
-
if(window.ActiveXObject){
-
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
-
}else if(window.XMLHttpRequest){
-
xmlHttp = new XMLHttpRequest();
-
}
-
}
-
-
function doRequest(){
-
createXMLHttpRequest();
-
var url = "servlet/ShowHintServlet?q=" + document.getElementById("email").value + "&timeStamp=" + new Date().getTime();
-
xmlHttp.onreadystatechange = handleStateChange;
-
xmlHttp.open("GET",url,true);
-
xmlHttp.send(null);
-
-
}
-
-
function handleStateChange(){
-
if(xmlHttp.readyState == 4){
-
if(xmlHttp.status == 200){
-
document.getElementById("hintbox").innerHTML = xmlHttp.responseText;
-
}
-
}
-
}
-
</script>
-
</head>
-
-
<body>
-
请输入你的手机号码:
-
<input type="text" name="email" id="email" onkeyup="doRequest()" />
-
<div id="hintbox"></div>
-
</body>
-
</html>
ShowHintServlet代码
- package ajax.study;
-
-
import java.io.IOException;
-
import java.io.PrintWriter;
-
-
import javax.servlet.ServletException;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
public class ShowHintServlet extends HttpServlet {
-
-
public void doGet(HttpServletRequest request, HttpServletResponse response)
-
throws ServletException, IOException {
-
-
response.setContentType("text/html");
-
String[] emails = {
-
"18789245070",
-
"13647579626",
-
"13648649621",
-
"18789273423",
-
"13876221345",
-
"13697542356",
-
"15248939447"
-
-
};
-
PrintWriter out = response.getWriter();
-
String q = request.getParameter("q");
-
String hint = "";
-
if(q.length()>0){
-
for(int i=0; i<emails.length; i++){
-
if(q.equalsIgnoreCase(emails[i].substring(0, q.length()))){
-
if(hint==""){
-
hint = emails[i];
-
}else{
-
hint = hint + " " + emails[i];
-
}
-
-
}
-
}
-
}
-
if(hint==""){
-
hint = "no suggestion";
-
}
-
out.println(hint);
-
out.flush();
-
out.close();
-
}
-
-
-
public void doPost(HttpServletRequest request, HttpServletResponse response)
-
throws ServletException, IOException {
-
doGet(request,response);
-
}
-
-
}
阅读(2657) | 评论(0) | 转发(1) |