本篇文章與上篇文章大體類似,不同的只不過是利用XMLHttpRequest非同步地向伺服器發送post請求。
除了register.jsp檔案,其餘三個檔案全部保持不變。
register.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script>function getXmlHttpRequest(){var xhr=null;if((typeof XMLHttpRequest)!='undefined'){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHttp");}return xhr;}function valiUsername(){var xhr=getXmlHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){var doc=xhr.responseText;document.getElementById('username_msg').innerHTML=doc;}else{document.getElementById('username_msg').innerHTML='sorry,system error...';}}else{document.getElementById('username_msg').innerHTML='checking...';}}var url="valiusername.do";xhr.open("post",url,true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send("username="+document.getElementById('n1').value);}</script></head><body><form action="register.do" method="post">username:<input type="text" name="username" id="n1" onblur="valiUsername();"><span style="color:red" id="username_msg"></span><br>password:<input type="password" name="password"><br><input type="submit" value="register"></form></body></html>
與上篇文章的get請求相比,post請求有3點不同:
① xhr.open("post",url,true);這裡將get 改為了post。
② xhr.send("username="+document.getElementById('n1').value);這裡參數不再為null,對於post請求,要傳遞的參數放在send方法裡。
③ 最重要的一點,必須在open和send方法之間加上代碼:xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");