PC
javascript 做客户端验证,比如是否为空,正则匹配,如果需要后台验证的(如是否唯一)需要用ajax访问后台,处理返回结果便可,下面给大家做个示范。
js:function checkLoginName() {var loginName = document.myform.loginName.value;//改成你的变量if (loginName == '' || loginName == null) { alert('用户名不能为空!'); return false;} else { var url = 'action.do?method=checkLoginName&loginName=' +loginName;//跳转的action send(url);}}
var xmlHttp;function createXmlHttp() {if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest();} else if (window.ActiveXObject) { xmlHttp = new ActiveXObject('MIcrosoft.XMLHttp');}}function send(url) {createXmlHttp();xmlHttp.open('GET', url, true);xmlHttp.onreadystatechange = processRequest;xmlHttp.send(null);}function processRequest() {if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { var myfont = document.getElementById('name');//这个name跟html页面的name是对应的,不用改 while (myfont.hasChildNodes()) { myfont.removeChild(myfont.firstChild); } var text = document.createTextNode(); text.nodeValue = xmlHttp.responseText; myfont.appendChild(text); }}}-----------------------------------------------------------------------------------
action:public ActionForward checkLoginName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LoginDao dao=new LoginDao(); String loginName=request.getParameter('loginName'); loginName=new String(loginName.getBytes('ISO-8859-1'),'UTF-8'); System.out.println(loginName); int num=dao.check(loginName); if(num==0){ response.getWriter().println('可用'); response.getWriter().flush(); }else{ response.getWriter().println('已经使用'); response.getWriter().flush(); } return null;}-----------------------------------------------------------------------------------------
dao:public int check(String loginName){ Session ss=HibernateSessionFactory.getSession(); ss.beginTransaction(); Query q=ss.createQuery('select loginName from Login where loginName=''+loginName+'''); List list=q.list(); ss.getTransaction().commit(); ss.close(); return list.size();}----------------------------------------------------------------------------------------------------------------------html:
网络虽好,但要注意劳逸结合哦!
如果是青少年,小编在这里提示大家千万不能沉迷网络!