Ajax实现简单的验证:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function ajaxValid(){ var xhr=null; var username=document.getElementById("username").value; //创建XMLHttpRequst对象,今后主要靠此对象进行与后台交互 if(window.ActiveXObject){ //IE5,6创建对象的方式 xhr=new ActiveXObject("Microsoft.XMLHTTP"); }else{ xhr=new XMLHttpRequest(); } //打开连接 xhr.open("get", ‘/Web030Ajax/AjaxServlet?username=‘+username); //发送请求 xhr.send(null); xhr.onreadystatechange=function(){ //readyState码,0代表未初始化,1正在加载2已加载3正在交互4完成 if(xhr.readyState==4){ //服务器响应码,200成功 if(xhr.status==200){ // console.log(‘成功‘); var jsondata=JSON.parse(xhr.responseText); //alert(jsondata.info); document.getElementById("info").innerHTML=jsondata.info; } } }; } </script> </head> <body> <form action=""> <table> <tr> <td>用户名</td> <td><input type="text" name="username" id="username" onblur="ajaxValid()"/><span id="info"></span></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password" id="password"/></td> </tr> </table> </form> </body> </html>
servlet端
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String username=request.getParameter("username"); PrintWriter out=response.getWriter(); if(username.equals("admin")){ out.print("{\"info\":\"exit\"}"); }else{ out.print("{‘info‘:‘ok‘}"); } }
省份
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function ff(){ var selected=document.getElementById("selected1"); selected.onclick=function (){ var xhr=null; xhr=new XMLHttpRequest(); xhr.open("post","/Web030Ajax/Province"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//注意这句话的顺序 xhr.send(null); xhr.onreadystatechange=function (){ if(xhr.readyState==4){ var prostr=xhr.responseText; var arry=JSON.parse(prostr); document.getElementById("selected").innerHTML=‘‘; for(var i=0;i<arry.length;i++){ document.getElementById("selected").innerHTML+=‘<option>‘+arry[i]+‘</option>‘; } } }; } } </script> </head> <body > <form action="" > <select id="selected"> </select> <input type="button" value="dianwo" id="selected1"> </form> </body> </html>
servlet端
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setCharacterEncoding("UTF-8"); PrintWriter out=response.getWriter(); List<String> provinces=new ArrayList<String>(); provinces.add("山东"); provinces.add("北京"); provinces.add("上海"); String jsondata=JSONArray.fromObject(provinces).toString(); out.print(jsondata); out.close(); }
时间: 2024-11-07 07:44:24