发布网友 发布时间:2022-04-23 04:44
共1个回答
热心网友 时间:2022-04-23 06:13
//javaScript部分: var xmlHttpRequest; function createXmlHttpRetuest() { if (window.ActiveXObject) { try { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } return xmlHttpRequest; } else if (window.XMLHttpRequest) { return new XMLHttpRequest(); } } function validate(field) { if (trim(field.value).length != 0) { createXmlHttpRetuest(); url = "validate!validateIsUserNameExist.action?user.userId =" + field.value; xmlHttpRequest.open('post', url, true); xmlHttpRequest.setRequestHeader("if-Modified-Since", "0"); xmlHttpRequest.onreadystatechange = function() { var responseStr = trim(xmlHttpRequest.responseText); if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { if (responseStr != '') { document.getElementById("isExitUserId").innerHTML = "<font color='red'>" + responseStr + "</font>"; } else { document.getElementById("isExitUserId").innerHTML = ""; } } else { alert('响应失败,错误码 :' + xmlHttpRequest.status); } }; xmlHttpRequest.send(null); } else { document.getElementById("isExitUserId").innerHTML = ""; } } html部分:当焦点离开输入域的时候触发事件:<td width="78%"> <input name="user.userId" type="text" class="text1" id="userId" size="10" maxlength="10" onblur="validate(this)"> <span id="isExitUserId"></span> </td> Action部分:/** * 利用Ajax判断用户名是否存在 * * @author Jeelon * @return SUCCESS * @throws IOException */ public String validateIsUserNameExist() throws IOException { if ((user = tUserBiz.findById(user.getUserId())) != null) { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/plain");// 设置输出为文字流 response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print("*该用户已存在"); out.flush(); out.close(); } return null; }