index.jsp:
1 <script type="text/javascript"> 2 function checkUser(username){//检测是否为空,不为空进行异步检测 3 if(username.value == ""){ 4 alert("请输入用户名!"); 5 username.focus(); 6 return; 7 } 8 else{ 9 createRequest('checkUser.jsp?user='+username.value); 10 } 11 } 12 function createRequest(url){//初始化对象,建立连接,并发送请求 13 var xmlhttp; 14 if(window.XMLHttpRequest){ 15 //code for IE7+,Firefox,Chrome,Opera,Safari 16 xmlhttp = new XMLHttpRequest(); 17 }else{ 18 //code for IE6,IE5 19 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 20 } 21 if(!xmlhttp){//如果不存在 22 alert("不能创建XMLHttpRequest对象实例"); 23 return false; 24 } 25 xmlhttp.onreadystatechange = function(){ 26 if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ 27 document.getElementById("myDiv").innerHTML=responseText; 28 } 29 } 30 xmlhttp.open("GET",url,true); 31 xmlhttp.send(); 32 } 33 34 35 </script>
body:
1 <body> 2 <form action="" method="post" name="form1"> 3 <center>用户名:<input type="text" id="username" size="32"> 4 <input type="submit" onclick="checkUser(form1.username)" value="check"></center><br> 5 <center>密码:<input type="password" id="pwd1" size="32"></center><br> 6 <center>确认密码:<input type="password" id="pwd2"></center><br> 7 <center>E-mail:<input type="text" id="email"></center><br> 8 <center><input type="submit" value="register"></center><br> 9 </form> 10 <center><div id="myDiv"></div></center> 11 </body>
checkUser.jsp:
1 <% 2 String[] userList = {"baidu","taobao","qq"}; 3 String user = new String(request.getParameter("user").getBytes("ISO-8859-1"),"UTF-8"); 4 Arrays.sort(userList); 5 int result=Arrays.binarySearch(userList, user); 6 System.out.println(user); 7 if(result > -1){ 8 out.print("恭喜您,该用户没有注册"); 9 }else{ 10 out.print("该用户已经被注册"); 11 } 12 %>
你的脚本有问题吧?responseText这个变量都没看到在哪儿申明的。修改为xmlhttp.responseText如何?
嗯嗯,是这样的,多谢啦
在控制台监听过没有?
var btn = document.getElementById("btnSubmit"); btn.onclick = function () { var request = getXMLHttpRequest(); //创建XMLHttpRequest对象 if (request) { request.open("get", "AjaxIsGetMethodSubmit.ashx?key=" + "12", true); request.onreadystatechange = function () { if (request.readyState == 4 && request.status == 200) { var txt = request.responseText; //XMLHttpRequest对象将响应的信息作为字符串返回 if (txt != "" && txt != "undefined") { alert(txt); } } } request.send(null); } };
没有返回值,你值得什么?代码中的print吗?.你的ajax请求并没有处理返回的字符串。
把27行 这句 document.getElementById("myDiv").innerHTML=responseText;
改成 document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
试试