Código HTML:
<script type="text/javascript"> var req; function validate() { var idField = document.getElementById("userID"); var url = "Validador?id=" + escape(idField.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("GET", url, true); req.onreadystatechange = callback; req.send(null); } function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid parseMessage(); } } } function parseMessage() { var message = req.responseXML.getElementsByTagName("message")[0]; setMessage(message.childNodes[0].nodeValue); } function setMessage(message) { var userMessageElement = document.getElementById("userIdMessage"); alert(userMessageElement); userMessageElement.innerHTML = "<font color=\"red\">" + message + " </font>"; } </script></head> <body> <input type="text" name="valor" id="userID" onkeyup="validate()"> </body>
Código HTML:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { throws ServletException, IOException { String targetId = request.getParameter("id"); if ((targetId != null) && !targetId.equals("hola")) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<message>invalid</message>"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<message>valid</message>"); } } )