<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% 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 'testajax.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"> <script> var request; // 发ajax 请求的 if (window.XMLHttpRequest) { // Mozilla,... request=new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE request = new ActiveXObject("Msxml2.XMLHTTP"); } //如果有返回值 以下事件会运行 /* request.onreadystatechange=function(){ if(request.readyState==4){ //服务器数据在哪? var ok=request.responseText; if(ok=="0"){ document.all.info.innerHTML="用户不可用"; }else{ document.all.info.innerHTML="用户合法"; } } }; */ request.onreadystatechange=function(){ if(request.readyState==4){ //服务器数据在哪? var ok=request.responseText; //返回的数组到这儿了,但是是string型 eval("var sz="+ok); document.all.shi.innerHTML=""; //如何 显示在下拉列表里 for(var i in sz){ var op=new Option(sz[i],sz[i]); document.all.shi.options.add(op); } } }; function checkName(){ // 目的 把你输入的姓名 去服务器检查一下 var name=document.all.stname.value; request.open("get","testajax?stname="+name); //向 testajax servlet 发请求 request.send("&r="+Math.random()); } //去服务回取市 function getShi(){ var name=document.all.sheng.value; request.open("get","testajax?sheng="+name); //向 testajax servlet 发请求 request.send(null); } </script> </head> <body> 登录名<input type="text" id="stname" /> <span id="info"></span> <button οnclick="checkName()" >检查是否同名</button> <hr/> <select id="sheng" οnchange="getShi()"> <option value="0">请输入一个省</option> <option value="hn">湖南</option> <option value="hb">湖北</option> <option value="gd">广东</option> </select> <select id="shi"></select> </body> </html>