寫在前面的話
在使用form表單的時候,一旦點擊提交觸發submit事件,一般會使得頁面跳轉,頁面間的跳轉等行為的控制權往往在后端,后端會控制頁面的跳轉及數據傳遞,但是在某些時候不希望頁面跳轉,或者說想要將控制權放在前端,通過js來操作頁面的跳轉或者數據變化。
一般這種異步的操作,我們都會想到ajax方式,因此在實現了功能后就整理了這篇文章,通過ajax方法實現form表單的提交并進行后續的異步操作。
常見的form表單提交方式
<!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表單的提交事件,數據傳輸至后端,由后端控制頁面跳轉和數據。
ajax實現form提交方式
修改完成后代碼如下:
<!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>
新聞熱點
疑難解答
圖片精選