使用ajax方法实现form表单的提交
生活随笔
收集整理的這篇文章主要介紹了
使用ajax方法实现form表单的提交
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
在使用form表單的時(shí)候,一旦點(diǎn)擊提交觸發(fā)submit事件,一般會使得頁面跳轉(zhuǎn),頁面間的跳轉(zhuǎn)等行為的控制權(quán)往往在后端,后端會控制頁面的跳轉(zhuǎn)及數(shù)據(jù)傳遞,但是在某些時(shí)候不希望頁面跳轉(zhuǎn),或者說想要將控制權(quán)放在前端,通過js來操作頁面的跳轉(zhuǎn)或者數(shù)據(jù)變化。
一般這種異步的操作,我們都會想到ajax方式,因此在實(shí)現(xiàn)了功能后就整理了這篇文章,通過ajax方法實(shí)現(xiàn)form表單的提交并進(jìn)行后續(xù)的異步操作。
常見的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>點(diǎn)擊登錄按鈕后,即觸發(fā)form表單的提交事件,數(shù)據(jù)傳輸至后端,由后端控制頁面跳轉(zhuǎn)和數(shù)據(jù)。
ajax實(shí)現(xiàn)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({//幾個(gè)參數(shù)需要注意一下type: "POST",//方法類型dataType: "json",//預(yù)期服務(wù)器返回的數(shù)據(jù)類型url: "/users/login" ,//urldata: $('#form1').serialize(),success: function (result) {console.log(result);//打印服務(wù)端返回的數(shù)據(jù)(調(diào)試用)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>注意事項(xiàng)
- 在常用方式中,點(diǎn)擊的登錄按鈕的type為"submit"類型;
- 在常用方式中,form的action不為空;
- ajax方式中需要注意的是$.ajax方法中的參數(shù):dataType和data。
轉(zhuǎn)載于:https://my.oschina.net/u/3787897/blog/1635493
總結(jié)
以上是生活随笔為你收集整理的使用ajax方法实现form表单的提交的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 汉王人脸1000万用户后的第一人诞生
- 下一篇: 利用 Rize 来进行 UI 测试或 E