Ajax实现简单的验证:
<html> <head> <Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <title>Inserttitlehere</title> <scripttype="text/javascript"> functionajaxValid(){ varxhr=null; varusername=document.getElementById("username").value; //创建XMLHttpRequst对象,今后主要靠此对象进行与后台交互 if(window.ActiveXObject){ //IE5,6创建对象的方式 xhr=newActiveXObject("Microsoft.XMLHTTP"); }else{ xhr=newXMLHttpRequest(); } //打开连接 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('成功'); varjsondata=JSON.parse(xhr.responseText); //alert(jsondata.info); document.getElementById("info").innerHTML=jsondata.info; } } }; } </script> </head> <body> <formaction=""> <table> <tr> <td>用户名</td> <td><inputtype="text"name="username"id="username"onblur="ajaxValid()"/><spanid="info"></span></td> </tr> <tr> <td>密码</td> <td><inputtype="password"name="password"id="password"/></td> </tr> </table> </form> </body> </html>
servlet端
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ //TODOAuto-generatedmethodstub Stringusername=request.getParameter("username"); PrintWriterout=response.getWriter(); if(username.equals("admin")){ out.print("{\"info\":\"exit\"}"); }else{ out.print("{'info':'ok'}"); } }
省份
<head> <Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <title>Inserttitlehere</title> <scripttype="text/javascript"> functionff(){ varselected=document.getElementById("selected1"); selected.onclick=function(){ varxhr=null; xhr=newXMLHttpRequest(); xhr.open("post","/Web030Ajax/Province"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//注意这句话的顺序 xhr.send(null); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ varprostr=xhr.responseText; vararry=JSON.parse(prostr); document.getElementById("selected").innerHTML=''; for(vari=0;i<arry.length;i++){ document.getElementById("selected").innerHTML+='<option>'+arry[i]+'</option>'; } } }; } } </script> </head> <bodyonload="ff()"> <formaction=""> <selectid="selected"> </select> <inputtype="button"value="dianwo"id="selected1"> </form> </body> </html>
servlet端
protectedvoiddoPost(HttpServletRequestrequest,IOException{ //TODOAuto-generatedmethodstub response.setCharacterEncoding("UTF-8"); PrintWriterout=response.getWriter(); List<String>provinces=newArrayList<String>(); provinces.add("山东"); provinces.add("北京"); provinces.add("上海"); Stringjsondata=JSONArray.fromObject(provinces).toString(); out.print(jsondata); out.close(); }