ajax原理,验证码生成原理

什么是ajax  

AJAX:”Asynchronous JavaScript and XML”

中文意思:异步JavaScript和XML

 指一种创建交互式网页应用的网页开发技术。

 

不是指一种单一的技术,而是有机地利用了一系列相关的技术:

简单理解为:JavaScript + XMLHttpRequest + CSS +服务器端 的集合

普通的网页请求回执过程(请求响应模式 同步模式)

 

ajax 网页应用 异步请求回执过程:通过和普通模式相比,就感觉ajax方式,就好比专门请了一个人去做一一件事,互不影响。

AJAX优点
•     Ajax在本质上是一个浏览器端的技术
•     Ajax技术之主要目的在于局部交换客户端及服务器间之数据
•     这个技术的主角XMLHttpRequest 的最主要特点,在于能够不用重新载入整个版面来更新资料,也就是所谓的Refresh without Reload(轻刷新)
•     与服务器之间的沟通,完全是透过Javascript 来实行
•     使用XMLHttpRequest 本身传送的数据量很小,所以反应会更快,也就让网络程式更像一个桌面应用程序(如:webqq)
•     AJAX 就是运用Javascript 在后台悄悄帮你去跟服务器要资料,最后再由Javascript 或DOM 来帮你呈现结果,因为所有动作都是由Javascript 代劳,所以省去了网页重载的麻烦,使用者也感受不到等待的痛苦

XMLHttpRequest对象
•     Ajax应用程序的核心就是它。
•     XMLHttpRequest对象在IE浏览器和非IE浏览器中创建的方法不同。
•      function createXHR(){
var request;
if(XMLHttpRequest){
request=new XMLHttpRequest();//非ie浏览器
}else{
request =new ActiveXObject("Microsoft.XMLHTTP");//ie浏览器
}
return request;
}
•     简而言之:它可以异步从服务器端获取txt或者xml数据 json(json主流)
异步请求基本步骤
按照下面模式,XMLHttpRequest对象:
•     创建对象; - new  (叫助手过来)
•     创建请求; - open (告诉他要去做的事情)
•     注册事件; - onreadystatechange(注册状态改变执行的事件)
•     发送请求; - send (去吧)

创建XMLHttpRequest对象
•     一、先来创建XMLHttpRequest对象
•     在IE、Firefox、safari和Opera中创建该对象的JavaScript代码为:
     var xhr = new XMLHttpRequest();
•     在IE5/6中代码为:
     var xmlRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
      注意,JavaScript区分大小写。
设置异步对象参数并发送请求
•     二、为XMLHttpRequest对象设置请求参数
      1.GET方式
            1.1设置参数第一个参数 传递方式 第二个参数请求的页面 第三个参数 true异步 false同步
            xhr.open("GET", "GetAreasByAjax.ashx?isAjax=1", true);
     1.2GET方式请求可以设置浏览器不使用缓存
xhr.setRequestHeader("If-Modified-Since", "0");
或者 xhr.open("GET", "GetAreasByAjax.ashx?_="+Math.random(), true);
     1.3发送: xhr.send(null);//GET方式
     2.POST方式:
       1.1设置参数:xhr.open("POST", "GetAreasByAjax.aspx", true);
       1.2添加请求头:xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");(post方式一定要加)
       1.3发送:xhr.send("isAjax=1&na=123");//POST方式
设置回调函数
      异步使用XMLHttpRequest对象
      异步使用XMLHttpRequest对象时,必须使用:onreadystatechange事件。
     使用模式应该是:
•     创建该对象;-new
•     打开请求;-open
•     设置readystatechange事件触发一个回调函数;

•     发送请求;-send
       注:在回调函数中检查readyState属性,看数据是否准备就绪(是否等于4)。
•     如果没有准备好,隔一段时间再次检查。因为数据没有下载完时,我们无法使用它的属性和方法。
•     如果已经准备好,就继续往下执行;
编写回调函数
1.在xhr.send之前添加设置回调函数代码:
xhr.onreadystatechange = watching;
2.回调函数
function watching() {
       if (xhr.readyState == 4) {//请求状态
           if (xhr.status == 200) {//服务器返回的状态码
               var msg = xhr.responseText; //服务器返回的字符串
           } else alert("服务器错误!" + ajaxH.status);
       }
}
异步对象readyState属性
•     readyState属性
       readyState属性指出了XMLHttpRequest对象在发送/接收数据过程中所处的几个状态。XMLHttpRequest对象会经历5种不同的状态。
•     0:未初始化。new完后;
•     1:已打开。对象已经创建并初始化,但还未调用send方法
•     2:已发送。已经调用send 方法,但该对象正在等待状态码和头的返回;
•     3:正在接收。已经接收了部分数据,但还不能使用该对象的属性和方法,因为状态和响应头不完整;
•     4:已加载。所有数据接收完毕
XMLHttpRequest常用方法

XMLHttpRequest常用属性

 

Json--B/S结构数据传递格式

  • AJAX传递复杂数据如果自己进行格式定义的话会经历组装、解析的过程,因此AJAX中有一个事实上的数据传输标准JSon。Json(是一个标准,就像 XML一样,Json规定了对象以什么样的格式保存为一个字符串)将复杂对象序列化为一个字符串,在浏览器端再将字符串反序列化为JavaScript可以读取的对象。看一下Json的格式。Json被几乎所有语言支持。var json=[{"a":"1","name":"sun"}];
  • C#中将.Net对象序列化为Json字符串的方法:JavaScriptSerializer().Serialize(p),JavaScriptSerializer在System.Web.Extensions.dll中,是.Net3.x中新增的类。
    完整:System.Web.Script.Serialization.JavaScriptSerializer

//ajax 请求常见问题

1、请求的路径中不能包含中

2、不让get请求读取浏览器缓冲 

1) url的?后设置随机数

2) 在请求头中添加xhr.setRequestHeader("If-Modified-Since", "0");

3、url传参 如果内容中有中文,应该进行url编码

4、区分xhr.readyState和xhr.status

5、区分大小写

 上面这些材料是之前,从网络收集到的简单易懂,就收藏在本地笔记了,现在拿出来跟大家一起分享,如果这篇文章作者看到,本人却无抄袭之意,就是为了学习技术。望谅解。

下面是自己根据ajax的原理实现的登录,验证码生成原理来操作,本案例是将密码和用户名记入session了,也是为了记住一个知识点,在一本处理程序中若要使用session必须实现System.Web.SessionState命名空间下的IRequiresSessionState接口。废话不多说,上demo

 Login.html

复制代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var xhr = createXHR();
        function createXHR() {
            var request;
            //非IE浏览器创建Xmlxhr对象
            if (XMLHttpRequest) {
                request = new XMLHttpRequest();
            } else {
                //IE浏览器创建Xmlxhr对象
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return request;
        };
        window.onload = function () {
            document.getElementById("btnLogin").onclick = function () {
                var name = document.getElementById("uid").value;
                var pwd = document.getElementById("pwd").value;
                var webCode = document.getElementById("webCode").value;
                var data = "n=" + name + "&p=" + pwd + "&c=" + webCode;
                xhr.open("POST", "Login.ashx", true);
                //在post的时候一定加上header
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            var msg = xhr.responseText;
                            if (msg == 1) {
                                alert('登录成功');
                            } else if (msg == 2) {
                                alert('验证码输入错误');
                            } else {
                                alert('用户名或者密码错误');
                            }
                        }
                    }

                };
                xhr.send(data);
            };
            document.getElementById("imgCode").onclick = function () {
                var ran = Math.random();
                //请求地址加上随机数参数,目的就是为了让每次请求的地址不同,不让验证码缓存
                xhr.open("GET", "MakeIdentityingCode.ashx?_r=" + ran, true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            document.getElementById("imgCode").src = "MakeIdentityingCode.ashx?_r=" + ran;
                        }
                    }
                };
                xhr.send(null);
            };
        };
       
    </script>
</head>
<body>
    <table border="0" cellpadding="0" cellspacing="0" style="width: 350px">
        <tr>
            <td>
                用户名:
            </td>
            <td>
                <input type="text" id="uid" value="" />
            </td>
        </tr>
        <tr>
            <td>
                密码:
            </td>
            <td>
                <input type="text" id="pwd" value="" />
            </td>
        </tr>
        <tr>
            <td>
                验证码:
            </td>
            <td>
                <input type="text" id="webCode" /><img alt="验证码" style="cursor: pointer;" id="imgCode"
                    title="验证码" src="MakeIdentityingCode.ashx" height="23px" width="80px" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="button" value="登录" id="btnLogin" /><input type="button" id="btnCancel"
                    value="取消" />
            </td>
        </tr>
    </table>
</body>
</html>
复制代码

Login.ashx一般处理程序页

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Web;
using  System.Web.SessionState;
namespace  IdentifyingCode
{
     /// <summary>
     /// Login 的摘要说明  在一般处理程序中若要操作session 则一定要实现IRequiresSessionState接口,否则会报错
     /// </summary>
     public  class  Login : IHttpHandler, IRequiresSessionState
     {
 
         public  void  ProcessRequest(HttpContext context)
         {
             context.Response.ContentType = "text/plain" ;
             string  userName = context.Request.Form[ "n" ];
             string  userPwd = context.Request.Form[ "p" ];
             string  code = context.Request.Form[ "c" ];
             if  (code != context.Session[ "code" ].ToString())
             {
                 context.Response.Write( "2" );
                 context.Response.End();
             }
             if  (userName == "admin"  && userPwd == "admin" )
             {
                 context.Response.Write( "1" );
             }
             else
             {
                 context.Response.Write( "3" );
             }
         }
 
         public  bool  IsReusable
         {
             get
             {
                 return  false ;
             }
         }
     }
}

 IdentifyingCode.ashx生成验证码一般处理程序

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Web;
using  System.Drawing;
using  System.Text;
using  System.Web.SessionState;
namespace  IdentifyingCode
{
     /// <summary>
     /// MakeIdentityingCode 的摘要说明 在一般处理程序中若要操作session 则一定要实现IRequiresSessionState接口,否则会报错
     /// </summary>
     public  class  MakeIdentityingCode : IHttpHandler, IRequiresSessionState
     {
         public  void  ProcessRequest(HttpContext context)
         {
             context.Response.ContentType = "image/jpeg" ;
             //将验证码存入session
             string  sessionCode = CreateRandom();
             context.Session[ "code" ] = sessionCode;
             //画板
             using  (Bitmap bitmap = new  Bitmap(80, 25))
             {
                 //画笔
                 using  (Graphics g = Graphics.FromImage(bitmap))
                 {
                     //把画板填充成红色(默认是黑色)
                     g.FillRectangle(Brushes.Red, 0, 0, bitmap.Width, bitmap.Height);
                     //填充白色,留两像素的红色边框
                     g.FillRectangle(Brushes.White, 1, 1, bitmap.Width - 2, bitmap.Height - 2);
                     //将验证码写入
                     g.DrawString(sessionCode, new  Font( "楷体" , 12), Brushes.Red, new  PointF(5, 5));
                     //保存到输出流中
                     bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                 }
             }
 
         }
         /// <summary>
         /// 生成6位的随机数 简单模拟生成的验证码
         /// </summary>
         /// <param name="n"></param>
         /// <returns></returns>
         private  string  CreateRandom()
         {
             string  code = "壹贰叁肆伍陆柒捌玖零" ;
             Random r = new  Random();
             StringBuilder sb = new  StringBuilder();
             for  ( int  i = 0; i < 4; i++)
             {
                 int  index = r.Next(0, 10);
                 sb.Append(code[index]);
             }
             return  sb.ToString();
         }
         public  bool  IsReusable
         {
             get
             {
                 return  false ;
             }
         }
     }
}

 只是一个简单的demo为了不让自己以后忘记,好记性不如烂笔头!!

下载demo:IdentifyingCode.rar

博客地址:http://www.cnblogs.com/wolf-sun/
博客版权:本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。
如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步!
再次感谢您耐心的读完本篇文章。http://www.cnblogs.com/wolf-sun/p/3256682.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值