jQuery,Ashx发送站内信
之前的项目有个发送站内短信的功能,今天闲来无事,就修改了一下程序,用jquery+ashx来实现一下,无刷新发送留言,欢迎大家拍砖。
1.验证码实现:

<%@ WebHandler Language="C#" Class="ValidateCode" %>
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
public class ValidateCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//特别注意,如不加,单击验证图片'看不清换一张',无效果.
this.CreateCheckCodeImage(GenerateCheckCode(context), context);
}
public bool IsReusable
{
get
{
return false;
}
}
private string GenerateCheckCode(HttpContext context)
{
string chkCode = string.Empty;
//颜色列表,用于验证码、噪线、噪点
Color[] color ={ Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange,
Color.Brown, Color.DarkBlue };
//字体列表,用于验证码
string[] font ={ "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh",
"PMingLiU", "Impact" };
//验证码的字符集,去掉了一些容易混淆的字符
char[] character ={ '2', '3', '4', '5', '6', '8', '9', 'A', '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 = 0; i < 4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//保存验证码的Cookie
HttpCookie anycookie = new HttpCookie("validateCookie");
anycookie.Values.Add("ChkCode", chkCode);
context.Response.Cookies["validateCookie"].Values["ChkCode"] = chkCode;//也可以存到Seesion里.
// context.Response.Cookies.Add(new HttpCookie("CheckCode", chkCode));
//context.Session["CheckCode"] = checkCode;
return chkCode;
}
private void CreateCheckCodeImage(string checkCode, HttpContext context)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap(60, 25);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 0; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 0; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
public class ValidateCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//特别注意,如不加,单击验证图片'看不清换一张',无效果.
this.CreateCheckCodeImage(GenerateCheckCode(context), context);
}
public bool IsReusable
{
get
{
return false;
}
}
private string GenerateCheckCode(HttpContext context)
{
string chkCode = string.Empty;
//颜色列表,用于验证码、噪线、噪点
Color[] color ={ Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange,
Color.Brown, Color.DarkBlue };
//字体列表,用于验证码
string[] font ={ "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh",
"PMingLiU", "Impact" };
//验证码的字符集,去掉了一些容易混淆的字符
char[] character ={ '2', '3', '4', '5', '6', '8', '9', 'A', '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 = 0; i < 4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//保存验证码的Cookie
HttpCookie anycookie = new HttpCookie("validateCookie");
anycookie.Values.Add("ChkCode", chkCode);
context.Response.Cookies["validateCookie"].Values["ChkCode"] = chkCode;//也可以存到Seesion里.
// context.Response.Cookies.Add(new HttpCookie("CheckCode", chkCode));
//context.Session["CheckCode"] = checkCode;
return chkCode;
}
private void CreateCheckCodeImage(string checkCode, HttpContext context)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap(60, 25);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 0; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪音点
for (int i = 0; i < 0; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
将验证码存入cookie中。
2.发送消息
<script type="text/javascript">
$(function()
{
$("#btn").bind("click",sendMsg);
}
)
function sendMsg()
{
var cookie= getCookie('validateCookie').split('=')[1];
//先验证表单非空 然后验证存入cookie的验证码是否正确
if(cookie!=$("#txtName")[0].value.toUpperCase()) //验证cookie
{
alert('验证码错误');
$("#txtName")[0].focus();
}
else
{
$.ajax({
type: "get",
url: "/ashx/test.ashx",
data:{"title":$("#txtName")[0].value,"userid":'<%= userid %>'},
beforeSend: function(XMLHttpRequest){
//ShowLoading();
},
success: function(data, textStatus){
alert('OK');
},
complete: function(XMLHttpRequest, textStatus){
//HideLoading();
},
error: function(){
alert('error');
}
});
}
}
</script>
操作cookie的js
<script>
// 保存 Cookie
function setCookie ( name, value )
{
expires = new Date();
expires.setTime(expires.getTime() + (1000 * 86400 * 365));
document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}
// 获取 Cookie
function getCookie ( name )
{
cookie_name = name + "=";
cookie_length = document.cookie.length;
cookie_begin = 0;
while (cookie_begin < cookie_length)
{
value_begin = cookie_begin + cookie_name.length;
if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
{
var value_end = document.cookie.indexOf ( ";", value_begin);
if (value_end == -1)
{
value_end = cookie_length;
}
return unescape(document.cookie.substring(value_begin, value_end));
}
cookie_begin = document.cookie.indexOf ( " ", cookie_begin) + 1;
if (cookie_begin == 0)
{
break;
}
}
return null;
}
// 清除 Cookie
function delCookie ( name )
{
var expireNow = new Date();
document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
}
</script>
$(function()
{
$("#btn").bind("click",sendMsg);
}
)
function sendMsg()
{
var cookie= getCookie('validateCookie').split('=')[1];
//先验证表单非空 然后验证存入cookie的验证码是否正确
if(cookie!=$("#txtName")[0].value.toUpperCase()) //验证cookie
{
alert('验证码错误');
$("#txtName")[0].focus();
}
else
{
$.ajax({
type: "get",
url: "/ashx/test.ashx",
data:{"title":$("#txtName")[0].value,"userid":'<%= userid %>'},
beforeSend: function(XMLHttpRequest){
//ShowLoading();
},
success: function(data, textStatus){
alert('OK');
},
complete: function(XMLHttpRequest, textStatus){
//HideLoading();
},
error: function(){
alert('error');
}
});
}
}
</script>
操作cookie的js
<script>
// 保存 Cookie
function setCookie ( name, value )
{
expires = new Date();
expires.setTime(expires.getTime() + (1000 * 86400 * 365));
document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}
// 获取 Cookie
function getCookie ( name )
{
cookie_name = name + "=";
cookie_length = document.cookie.length;
cookie_begin = 0;
while (cookie_begin < cookie_length)
{
value_begin = cookie_begin + cookie_name.length;
if (document.cookie.substring(cookie_begin, value_begin) == cookie_name)
{
var value_end = document.cookie.indexOf ( ";", value_begin);
if (value_end == -1)
{
value_end = cookie_length;
}
return unescape(document.cookie.substring(value_begin, value_end));
}
cookie_begin = document.cookie.indexOf ( " ", cookie_begin) + 1;
if (cookie_begin == 0)
{
break;
}
}
return null;
}
// 清除 Cookie
function delCookie ( name )
{
var expireNow = new Date();
document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
}
</script>
3.通过一般处理程序获取数据
public class Test : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string name = context.Request.QueryString["name"];
string userid = context.Request.QueryString["userid"];
Message msg = new Message();
msg.SendUserId = userid;
msg.AgentManName = name;
//...........msg赋值略
if (MessageManage.AddMessage(msg) > 0)
{
context.Response.Write("1");
}
else
{
context.Response.Write("0");
}
//jquery可以根据返回值 执行相应的操作
}
public bool IsReusable
{
get
{
return false;
}
}
}
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string name = context.Request.QueryString["name"];
string userid = context.Request.QueryString["userid"];
Message msg = new Message();
msg.SendUserId = userid;
msg.AgentManName = name;
//...........msg赋值略
if (MessageManage.AddMessage(msg) > 0)
{
context.Response.Write("1");
}
else
{
context.Response.Write("0");
}
//jquery可以根据返回值 执行相应的操作
}
public bool IsReusable
{
get
{
return false;
}
}
}
如果你不喜欢使用服务器段控件,就可以这样写,好了,今天就写到这里,灰常适合初学者看。
作者:Cat Qi
出处:http://qixuejia.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://qixuejia.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架