点滴积累【C#】---验证码,ajax提交
效果:
思路:
借用ashx文件创建四位验证,首先生成四位随机数字。然后创建画布,再将创建好的验证码存入session,然后前台进行button按钮将文本框中的值进行ajax请求到后台,和session中的验证码进行对比,成功返回true,失败返回false.
代码:
【前台】
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="verifycodeDemo.aspx.cs" Inherits="verifycodeDemo.verifycodeDemo" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>青苹果验证码例子</title>
<script src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//切换验证码
function ToggleCode(obj, codeurl) {
$("#" + obj).attr("src", codeurl + "?time=" + Math.random());
}
//ajax提交后台验证
function postAjax() {
var VerifyCodeValue = $("#txtVerifyCode").val();
$.ajax({
type: 'post',
dataType: "text",
url: "verifycodeDemo.aspx",
data: "action=comparison&VerifyCode=" + VerifyCodeValue,
cache: false,
async: false,
success: function (msg) {
if (msg == "false") {
alert("验证失败!sorry,青苹果");
ToggleCode("Verify_codeImag", "VerifyCode.ashx");
$("#txtVerifyCode").val("");
}
else {
alert("验证成功!hello,青苹果!");
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtVerifyCode" />
<img src="VerifyCode.ashx" id="Verify_codeImag" alt="点击切换验证码" style="CURSOR: pointer" width="65" height="25" title="点击切换验证码" onclick="ToggleCode(this.id, 'VerifyCode.ashx');return false;" />
<input type="button" value="青苹果验证码" onclick="postAjax()" />
</div>
</form>
</body>
</html>
【后台】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace verifycodeDemo
{
public partial class verifycodeDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
string VerifyCodeValue = Request.Params["VerifyCode"];
if (action == "comparison")
{
string Msg = "true";
//对session中存储的验证码对比
if (HttpContext.Current.Session["dt_session_code"] == null || VerifyCodeValue.ToLower() != HttpContext.Current.Session["dt_session_code"].ToString().ToLower())
{
Msg = "false";//验证码输入不正确
}
Response.Write(Msg);
Response.End();
} }
}
}
【ashx文件】
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState; namespace ESoftMS.Web.Frame
{
/// <summary>
/// VerifyCode 的摘要说明 青苹果(www.cnblogs.com/xinchun)
/// </summary>
public class VerifyCode : IHttpHandler, IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
int codeW = ;
int codeH = ;
int fontSize = ;
string chkCode = string.Empty;
//颜色列表,用于验证码、噪线、噪点
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
//字体列表,用于验证码
string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
//验证码的字符集,去掉了一些容易混淆的字符
char[] character = { '', '', '', '', '', '', '', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
Random rnd = new Random();
//生成验证码字符串
for (int i = ; i < ; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//写入Session
context.Session["dt_session_code"] = chkCode;
//创建画布
Bitmap bmp = new Bitmap(codeW, codeH);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//画噪线
for (int i = ; i < ; i++)
{
int x1 = rnd.Next(codeW);
int y1 = rnd.Next(codeH);
int x2 = rnd.Next(codeW);
int y2 = rnd.Next(codeH);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//画验证码字符串
for (int i = ; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, fontSize);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * + , (float));
}
////画噪点
//for (int i = 0; i < 1; i++)
//{
// int x = rnd.Next(bmp.Width);
// int y = rnd.Next(bmp.Height);
// Color clr = color[rnd.Next(color.Length)];
// bmp.SetPixel(x, y, clr);
//}
//清除该页输出缓存,设置该页无缓存
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds();
context.Response.Expires = ;
context.Response.CacheControl = "no-cache";
context.Response.AppendHeader("Pragma", "No-Cache");
//将验证码图片写入内存流,并将其以 "image/Png" 格式输出
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
catch (Exception)
{ }
finally
{
g.Dispose();
bmp.Dispose();
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}
Demo下载:
http://files.cnblogs.com/xinchun/verifycodeDemo.rar
点滴积累【C#】---验证码,ajax提交的更多相关文章
- Ajax提交表单时验证码自动验证 php后端验证码检测
本文通过源码展示如何实现表单提交前,验证码先检测正确性,不正确则不提交表单,更新验证码. 1.前端代码 index.html <!DOCTYPE html> <html> &l ...
- python_way day21 Django文件上传Form方式提交,原生Ajax提交字符处啊,Django文件上传之原生Ajax方式、jQuery Ajax方式、iframe方式,Django验证码,抽屉示例,
python_way day21 1.Django文件上传至Form方式 2.原生Ajax文件上传提交表单 使用原生Ajax好处:不依赖jquery,在发送一个很小的文件或者字符串的时候就可以用原生A ...
- javascript表单的Ajax 提交插件的使用
Ajax 提交插件 form.js 表单的下载地址:官方网站:http://malsup.com/jquery/form/ form.js 插件有两个核心方法:ajaxForm()和ajaxSubmi ...
- Ajax 提交KindEditor的数据
这次我是在EasyUI中使用了KindEditor的编辑器,按照官方给的代码,总是无法获取编辑器里面的值(内容),如下: KindEditor.ready(function (K) { ...
- jquery实现ajax提交表单信息
最近在思考优化项目,想自己扩展一个jquery自动获取表单中的数据进行ajax提交.本人没有完整性学习jquery,基本上是现学现找,有点困难. 主要是扩展和拼接json转对象 很简单,附上代码: ; ...
- ajax提交form表单
1. ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单. 2. from视图部分 <form id="loginF ...
- 【ajax 提交表单】多种方式的注意事项
在业务中,可能因为表单内容过于庞大,字段过于繁杂,如果人为去拼接的话 ,需要耗费大量的时间和精力,与此同时,代码看上去也是冗余不堪. 所以,提交表单的时候如果能整个表单数据整体提交,那是非常开心的事情 ...
- Ajax提交参数的值中带有html标签不能提交成功的解决办法(ASP.NET)
最近在公司做资源及文章上传功能遇到一个小问题,被坑了好半天. 该功能就类似利用富文本编辑器发布信息,但是用Ajax提交数据,因此提交参数值中不可避免的含有html标签. 在本地运行代码一直没问题,总是 ...
- ajax提交form表单资料详细汇总
一.ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单.通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新.这意味 ...
随机推荐
- new placement 的使用
#include <iostream> #include "TModel.h" int main() { ]; std::cout<<"Sourc ...
- JavaScript 时间与日期处理实战:你肯定被坑过
本部分的知识图谱请参考编程语言知识图谱-时间与日期. 本文JavaScript 时间与日期处理实战:你肯定被坑过从属于笔者的Web 前端入门与最佳实践中 JavaScript 入门与最佳实践系列文章. ...
- java多线程处理导入数据拆分List集合 同步处理插入数据
原文:https://www.2cto.com/kf/201612/581174.html import org.apache.log4j.Logger; import org.apache.poi. ...
- php判断手机客户端
<?php // check if wap function check_wap(){ if(stristr($_SERVER['HTTP_VIA'],"wap")){// ...
- fmri 分析数据 fsl & spm 两大平台比对
基于下面这份ppt:Comparing SPM and FSL, by lChris Rorden fsl & spm都是免费的,都很受欢迎.spm更受欢迎. 两者的区别在于何时利用norma ...
- 实现自动文本摘要(python,java)
参考资料:http://www.ruanyifeng.com/blog/2013/03/automatic_summarization.html http://joshbohde.com/blog/d ...
- scrapy-splash抓取动态数据例子八
一.介绍 本例子用scrapy-splash抓取界面网站给定关键字抓取咨询信息. 给定关键字:个性化:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信息 ...
- scrapy-splash抓取动态数据例子七
一.介绍 本例子用scrapy-splash抓取36氪网站给定关键字抓取咨询信息. 给定关键字:个性化:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信 ...
- ThreadLocal的简单应用
概括起来说,对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式.前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一 ...
- mysql有关问题之:the security settings could not be applied to
mysql问题之:the security settings could not be applied to 转自:http://www.myexception.cn/mysql/503556.htm ...