首先提出一個問題:在做網站開發的時候,用到了驗證碼來防止惡意提交表單,那么要如何實現當驗證碼錯誤時,只是刷新一下驗證碼,而其它填寫的信息不改變?
先說一下為什么有這個需求:以提交注冊信息頁面為例,一般注冊都需要用戶填一個驗證碼信息(防止機器惡意注冊),並且這個驗證碼會提交到后台去進行比對,若是錯了則不會檢查其他提交信息而直接返回瀏覽器端提示驗證碼錯誤。若是簡單地用form表單直接將數據提交到指定的url,當驗證碼填寫錯誤的信息返回瀏覽器端的時候,不可避免整個頁面都會重新刷新一次,這是用戶所不想要的,因為其它的一些正確信息還需要重新再填一次,這樣就造成用戶體驗不太好。而這個問題就可以通過Ajax異步提交表單來實現。(這只是其中一種解決方案)
下面就來看看具體的實現:
前台Html代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Ajax異步提交表單之檢查驗證碼</title> </head> <body> <form action="javascript:AjaxPostData()" method="post"> <label>用戶名:</label> <input name="account" class="form-control" id="account" type="text" placeholder="用戶名" required="required" /> <label>密碼:</label> <input name="password" class="form-control" id="password" type="password" placeholder="密碼" required="required" /> <label>驗證碼:</label> <img id="valiCode" class="validcode" src="/Home/GetValidateCode" alt="驗證碼" title="點擊刷新" /> <input name="code" class="form-control" id="code" type="text" placeholder="驗證碼" required="required" /> <button type="submit">提交</button> </form> <script src="~/Scripts/jquery-1.12.1.min.js"></script> <script> //刷新驗證碼 function RefreshValiCode() { document.getElementById("valiCode").src = "/GetValidateCode?time=" + (new Date()).getTime(); } function AjaxPostData() { var code = document.getElementById("code").value; var account = document.getElementById("account").value; var password = document.getElementById("password").value; $.ajax({ url: '/User/Register',//數據提交到的目標url type: 'post',//post方式提交 async: true,//異步提交 data: {account: account, password: password, code: code },//提交的數據 success: function (data) {//發送成功的回調函數 if (data.success) { alert("注冊失敗!"); } else { alert("注冊成功!"); RefreshValiCode();//刷新驗證碼 document.getElementById("code").value = "";//置空輸入框 } }, error: function () { alert("請求失敗!請重新提交!"); } }); } </script> </body> </html>
注:jquery-1.12.1.min.js需要自己下載引用。
后台C#代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace Test.Controllers { public class UserController : Controller { /// <summary> /// 注冊 /// </summary> /// <param name="code">驗證碼</param> /// <returns></returns> [HttpPost] public ActionResult Register(string name, string password, string code) { //Session["RegisterCode"]在生成驗證碼的時候設置其值 if (string.IsNullOrWhiteSpace(code) || Session["RegisterCode"].ToString().ToUpper() != code.ToUpper()) { return Json(new { success = false}); } else { //其它操作... return Json(new { success = true}); } } } }
此次知識分享就到這,敬請期待下一次的分享。^_^
<我的博客主頁>:http://www.cnblogs.com/forcheng/
<Wing工作室主頁>:http://www.wingstudio.org/
