ajax原理,验证码生成原理

什么是ajax  javascript

AJAX:”Asynchronous JavaScript and XML”html

中文意思:异步JavaScript和XMLjava

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

 

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

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

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

 

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对象
•     1、先来建立XMLHttpRequest对象
•     在IE、Firefox、safari和Opera中建立该对象的JavaScript代码为:
     var xhr = new XMLHttpRequest();
•     在IE5/6中代码为:
     var xmlRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
      注意,JavaScript区分大小写。
设置异步对象参数并发送请求
•     2、为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 请求常见问题

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

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

1) url的?后设置随机数

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

三、url传参 若是内容中有中文,应该进行url编码

四、区分xhr.readyState和xhr.status

五、区分大小写

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

下面是本身根据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

相关文章
相关标签/搜索