在使用form表單的時候,一旦點擊提交觸發submit事件,通常會使得頁面跳轉,頁面間的跳轉等行爲的控制權每每在後端,後端會控制頁面的跳轉及數據傳遞,可是在某些時候不但願頁面跳轉,或者說想要將控制權放在前端,經過js來操做頁面的跳轉或者數據變化。javascript
通常這種異步的操做,咱們都會想到ajax方式,所以在實現了功能後就整理了這篇文章,經過ajax方法實現form表單的提交併進行後續的異步操做。html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login test</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="login test"> </head> <body> <div id="form-div"> <form id="form1" action="/users/login" method="post"> <p>用戶名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p> <p>密 碼:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p> <p><input type="submit" value="登陸"> <input type="reset" value="重置"></p> </form> </div> </body> </html>
點擊登陸按鈕後,即觸發form表單的提交事件,數據傳輸至後端,由後端控制頁面跳轉和數據。前端
修改完成後代碼以下:java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login test</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="ajax方式"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> function login() { $.ajax({ //幾個參數須要注意一下 type: "POST",//方法類型 dataType: "json",//預期服務器返回的數據類型 url: "/users/login" ,//url data: $('#form1').serialize(), success: function (result) { console.log(result);//打印服務端返回的數據(調試用) if (result.resultCode == 200) { alert("SUCCESS"); } ; }, error : function() { alert("異常!"); } }); } </script> </head> <body> <div id="form-div"> <form id="form1" onsubmit="return false" action="##" method="post"> <p>用戶名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p> <p>密 碼:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p> <p><input type="button" value="登陸" onclick="login()"> <input type="reset" value="重置"></p> </form> </div> </body> </html>