最近使用Ajax技術通過XMLHttpRequest對象完成一個首頁的登入功能!
代碼如下:
<script type="text/javascript">//建立XMLHttpRequest對象function createXMLHttpRequest(){if(window.XMLHttpRequest){return xmlhttprequest=new XMLHttpRequest();}else{return xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP");}}//登入按鈕執行的方法function doStart(){var logname=document.getElementById("loginName").value;var logpass=document.getElementById("loginPsw").value;var userinfo="inAccount="+logname+"&inPsw="+logpass;var url="users/users_pswCheck.action";xmlhttprequest=createXMLHttpRequest();xmlhttprequest.onreadystatechange=getresultValue;xmlhttprequest.open("post",url,true);xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xmlhttprequest.send(userinfo);}//回調方法function getresultValue(){if(xmlhttprequest.readyState==4 && xmlhttprequest.status==200){var result=xmlhttprequest.responseText;if(result=="success"){window.location.href="index.jsp" rel="external nofollow" ;} else {document.getElementById("xiaoxi").innerHTML="登入失敗!";}}}//頁面的按鍵事件,即當按的是斷行符號鍵時觸發該事件function keybutton(){if(event.keyCode==13){ doStart(); return;} }</script>