现在的位置: 首页 > 综合 > 正文

jQuery,Ashx发送站内信

2012年03月24日 ⁄ 综合 ⁄ 共 6767字 ⁄ 字号 评论关闭

之前的项目有个发送站内短信的功能,今天闲来无事,就修改了一下程序,用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(6025);
        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(00, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2ftrue
);
            g.DrawString(checkCode, font, brush, 
22
);

            //画图片的前景噪音点
            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), 00, 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>

 

 

 

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;
        }
    }

}

 

 

 

如果你不喜欢使用服务器段控件,就可以这样写,好了,今天就写到这里,灰常适合初学者看。

 

 

 

 

【上篇】
【下篇】

抱歉!评论已关闭.