首先提出一个问题:在做网站开发的时候,用到了验证码来防止恶意提交表单,那么要如何实现当验证码错误时,只是刷新一下验证码,而其它填写的信息不改变?
先说一下为什么有这个需求:以提交注册信息页面为例,一般注册都需要用户填一个验证码信息(防止机器恶意注册),并且这个验证码会提交到后台去进行比对,若是错了则不会检查其他提交信息而直接返回浏览器端提示验证码错误。若是简单地用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/