正文
Ajax实现简单的验证:
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,HttpServletResponseresponse)throwsServletException,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(); }