<form action="#" method="post"> <input type="text" name="username" id="username"/> <input type="password" name="password" id="password"/> <input type="button" onclick="loginAjax()" value="ajax登錄"/> </form> <script type="text/javascript"> /* XMLHttpRequest i8+ 你口中所說的ajax 它是構建HTTP請求的javascript對象,在早期它是ActiveX對象形式存在, 服務器端和客戶端數據傳遞過程異步的問題,早期數據的傳遞一個字符串一個xml 實際上,ajax就是在javascript和xml之間創建一種異步傳輸的方式 xml:爲何出現xml文檔格式: 一種有格式方便進行管理和解析 它只不過是另一種Http請求而已,它和form表單原理是同樣,只不過不會刷新頁面進行一種異步的交互 */ function loginAjax(){ var username = document.getElementById("username").value; var password = document.getElementById("password").value; var params = "username="+username+"&password="+password; //建立一個(ajax)xhr對象 var xhr = new XMLHttpRequest(); //true代碼的是異步請求,執行成功和失敗回調函數 //請求的狀態, readyState //0:未初始化狀態 //1:載入請求的狀態 //2:載入完成狀態 //3:請求交互狀態 //4:請求完成狀態 //能夠捕獲服務器錯誤,知識點:status //500 服務器鏈接失敗 ---服務器關閉 //404 表明頁面找到 //400 Bad Request請求語法。url寫錯了,請求地址有問題 //405 請求方式有問題 springmvc methpd=RequestMethod.POST //200 表明交互成功,正確請求和響應 xhr.onreadystatechange = function(){ //ajax載入完成和服務器沒錯誤 if(this.readyState == 4 && this.status ==200){ alert(this.responseText) } }; //請求方式:post/get //get請求的方式以下: //xhr.open("get","http://localhost/keke_ajaxtest/xiaojie.jsp"+params,true); //xhr.send(); //post請求的方式以下: xhr.open("post","http://localhost/keke_ajaxtest/xiaojie.jsp",true); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); //發送數據,若是請求方式是post話send必定要設置參數 xhr.send(params);//發送 }; /* <form action="http://localhost/keke_ajaxtest/xiaojie.jsp" method="post"> <input type="text" name="username"/> <input type="text" name="password"/> <input type="submit" value="form登錄"/> </form>*/ </script>