AJAX示例一(注冊頁面用戶名驗證)


頁面展示代碼:

<tr>
<td class="altbg1" width="21%">用戶名:</td>
<td class="altbg2"><input id="userid" name="username" size="25" maxlength="25" type="text" onBlur="validate()">
<span id="usermsg"></span>
<script type="text/javascript">var req;function validate(){var username=document.getElementById("userid");var url="Validate.jsp?id="+escape(username.value);//escape用於對字符串進行編碼,可以對其中的字符任意值進行解析if(window.XMLHttpRequest) {                   //根據瀏覽器不同創建不同的reqreq = new XMLHttpRequest();} else if (window.ActiveXObject) {req = new ActiveXObject("Microsoft.XMLHTTP");}req.open("GET", url, true);//true為異步req.onreadystatechange = callback;req.send(null);}function callback() {if(req.readyState == 4) {if(req.status == 200) {//alert(req.responseText);var msg = req.responseXML.getElementsByTagName("msg")[0];//返回頁面是一個XML文件,解析該文件得到msg對象//alert(msg);        setMsg(msg.childNodes[0].nodeValue);//xml文本中第一個msg對象的值}}}function setMsg(msg) {//alert(msg);mdiv = document.getElementById("usermsg");if(msg == "invalid") {mdiv.innerHTML = "<font color='red'>username exists</font>";} else {mdiv.innerHTML = "<font color='green'>congratulations! you can use this username!</font>";}}</script>


Validate.jsp頁面:

<%
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-store"); //HTTP1.1
response.setHeader("Pragma", "no-cache"); //HTTP1.0
response.setDateHeader("Expires", 0); //prevents catching at proxy server
System.out.println(request.getParameter("id"));
//check the database
response.getWriter().write("<msg>valid</msg>");
%>




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: