AJAX入门实例

表单页面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'ajax.jsp' starting page</title>
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<script type="text/javascript">
   var req;
   function validate() {
    var user = document.getElementById("user");
    var url = "validate.jsp?user=" + escape(user.value);
    if(window.XMLHttpRequest) {
     req = new XMLHttpRequest();
    } else if(window.ActiveXObject) {
     req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.open("GET", url, true);
    req.onreadystatechange = callback;
    req.send(null);
   }
 
   function callback() {
    if(req.readyState == 4) {//
     if(req.status == 200) {//服务器返回客户端200,则证明成功返回
      //alert(req.responseText);//反馈的信息
      var msg = req.responseXML.getElementsByTagName("msg")[0];
      setMsg(msg.childNodes[0].nodeValue);
     }
    } else if(req.readyState == 1) {
     setMsg("ing");
     alert();//因为是本地信息,读取较快,不能看到这个过程,在这弹出一个框,会看到这个状态
    }
   }
 
   function setMsg(msg) {
    if(msg == "invalid")
     document.getElementById("usernamemsg").innerHTML = "<font color='red'>该用户名已存在</font>";
    else if(msg == "ing")
     document.getElementById("usernamemsg").innerHTML = "<font color='gray'>正在查询...</font>";
    else
     document.getElementById("usernamemsg").innerHTML = "<font color='green'>恭喜你,该用户名可用</font>";
   }
</script>
<body>
    <form action="">
    <input name="username" id="user" onblur="validate()"/><span id="usernamemsg"></span>
    </form>
</body>
</html>

数据在这个页面进行查询,我在这里没有连接数据库,直接返回了一个值

<%
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-store"); //HTTP1.1
response.setHeader("Pragma", "no-cache"); //HTTP1.0
response.setDateHeader("Expires", 0); //prevents catching at proxy server
System.out.println(request.getParameter("id"));
//check the database
response.getWriter().write("<msg>invalid</msg>");
%>

你可能感兴趣的:(jsp,Ajax,xml,cache,Microsoft)