zoukankan      html  css  js  c++  java
  • python第一百一十八天---ajax--图片验证码 + Session

    原生AJAX
      
    Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。

    1、XmlHttpRequest对象介绍
    XmlHttpRequest对象的主要方法:
     1 XmlHttpRequest对象的主要方法:
     2     a. void open(String method,String url,Boolen async)
     3    用于创建请求
     4 
     5    参数:
     6        method: 请求方式(字符串类型),如:POST、GET、DELETE...
     7        url:    要请求的地址(字符串类型)
     8        async:  是否异步(布尔类型)
     9 
    10 b. void send(String body)
    11     用于发送请求
    12 
    13     参数:
    14         body: 要发送的数据(字符串类型)
    15 
    16 c. void setRequestHeader(String header,String value)
    17     用于设置请求头
    18 
    19     参数:
    20         header: 请求头的key(字符串类型)
    21         vlaue:  请求头的value(字符串类型)
    22 
    23 d. String getAllResponseHeaders()
    24     获取所有响应头
    25 
    26     返回值:
    27         响应头数据(字符串类型)
    28 
    29 e. String getResponseHeader(String header)
    30     获取响应头中指定header的值
    31 
    32     参数:
    33         header: 响应头的key(字符串类型)
    34 
    35     返回值:
    36         响应头中指定的header对应的值
    37 
    38 f. void abort()
    39 
    40     终止请求
    View Code
    XmlHttpRequest对象的主要属性:
     1 a. Number readyState
     2    状态值(整数)
     3 
     4    详细:
     5       0-未初始化,尚未调用open()方法;
     6       1-启动,调用了open()方法,未调用send()方法;
     7       2-发送,已经调用了send()方法,未接收到响应;
     8       3-接收,已经接收到部分响应数据;
     9       4-完成,已经接收到全部响应数据;
    10 
    11     b. Function onreadystatechange
    12        当readyState的值改变时自动触发执行其对应的函数(回调函数)
    13 
    14     c. String responseText
    15        服务器返回的数据(字符串类型)
    16 
    17     d. XmlDocument responseXML
    18        服务器返回的数据(Xml对象)
    19 
    20     e. Number states
    21        状态码(整数),如:200、404...
    22 
    23     f. String statesText
    24        状态文本(字符串),如:OK、NotFound...
    View Code
    2、跨浏览器支持
      
    XmlHttpRequest
    IE7+, Firefox, Chrome, Opera, etc.
    ActiveXObject("Microsoft.XMLHTTP")
    IE6, IE5


    基于原生AJAX - Demo
     1 <!DOCTYPE html>
     2     <html>
     3     <head lang="en">
     4         <meta charset="UTF-8">
     5         <title></title>
     6     </head>
     7     <body>
     8 
     9         <h1>XMLHttpRequest - Ajax请求</h1>
    10         <input type="button" onclick="XmlGetRequest();" value="Get发送请求" />
    11         <input type="button" onclick="XmlPostRequest();" value="Post发送请求" />
    12 
    13         <script src="/statics/jquery-1.12.4.js"></script>
    14         <script type="text/javascript">
    15 
    16             function GetXHR(){
    17                 var xhr = null;
    18                 if(XMLHttpRequest){
    19                     xhr = new XMLHttpRequest();
    20                 }else{
    21                     xhr = new ActiveXObject("Microsoft.XMLHTTP");
    22                 }
    23                 return xhr;
    24 
    25             }
    26 
    27             function XhrPostRequest(){
    28                 var xhr = GetXHR();
    29                 // 定义回调函数
    30                 xhr.onreadystatechange = function(){
    31                     if(xhr.readyState == 4){
    32                         // 已经接收到全部响应数据,执行以下操作
    33                         var data = xhr.responseText;
    34                         console.log(data);
    35                     }
    36                 };
    37                 // 指定连接方式和地址----文件方式
    38                 xhr.open('POST', "/test/", true);
    39                 // 设置请求头
    40                 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
    41                 // 发送请求
    42                 xhr.send('n1=1;n2=2;');
    43             }
    44 
    45             function XhrGetRequest(){
    46                 var xhr = GetXHR();
    47                 // 定义回调函数
    48                 xhr.onreadystatechange = function(){
    49                     if(xhr.readyState == 4){
    50                         // 已经接收到全部响应数据,执行以下操作
    51                         var data = xhr.responseText;
    52                         console.log(data);
    53                     }
    54                 };
    55                 // 指定连接方式和地址----文件方式
    56                 xhr.open('get', "/test/", true);
    57                 // 发送请求
    58                 xhr.send();
    59             }
    60 
    61         </script>
    62 
    63     </body>
    64     </html>
    View Code


    jQuery Ajax
    jQuery其实就是一个JavaScript的类库,其将复杂的功能做了上层封装,使得开发者可以在其基础上写更少的代码实现更多的功能。
    jQuery 不是生产者,而是大自然搬运工。
    jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject
    注:2.+版本不再支持IE9以下的浏览器


     1 jQuery Ajax 方法列表
     2     jQuery.get(...)
     3                 所有参数:
     4                      url: 待载入页面的URL地址
     5                     data: 待发送 Key/value 参数。
     6                  success: 载入成功时回调函数。
     7                 dataType: 返回内容格式,xml, json,  script, text, html
     8 
     9 
    10             jQuery.post(...)
    11                 所有参数:
    12                      url: 待载入页面的URL地址
    13                     data: 待发送 Key/value 参数
    14                  success: 载入成功时回调函数
    15                 dataType: 返回内容格式,xml, json,  script, text, html
    16 
    17 
    18             jQuery.getJSON(...)
    19                 所有参数:
    20                      url: 待载入页面的URL地址
    21                     data: 待发送 Key/value 参数。
    22                  success: 载入成功时回调函数。
    23 
    24 
    25             jQuery.getScript(...)
    26                 所有参数:
    27                      url: 待载入页面的URL地址
    28                     data: 待发送 Key/value 参数。
    29                  success: 载入成功时回调函数。
    30 
    31 
    32             jQuery.ajax(...)
    33 
    34                 部分参数:
    35 
    36                         url:请求地址
    37                        type:请求方式,GET、POST(1.9.0之后用method)
    38                     headers:请求头
    39                        data:要发送的数据
    40                 contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
    41                       async:是否异步
    42                     timeout:设置请求超时时间(毫秒)
    43 
    44                  beforeSend:发送请求前执行的函数(全局)
    45                    complete:完成之后执行的回调函数(全局)
    46                     success:成功之后执行的回调函数(全局)
    47                       error:失败之后执行的回调函数(全局)
    48 
    49 
    50                     accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
    51                    dataType:将服务器端返回的数据转换成指定类型
    52                                    "xml": 将服务器端返回的内容转换成xml格式
    53                                   "text": 将服务器端返回的内容转换成普通文本格式
    54                                   "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
    55                                 "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
    56                                   "json": 将服务器端返回的内容转换成相应的JavaScript对象
    57                                  "jsonp": JSONP 格式
    58                                           使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
    59 
    60                                   如果不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string
    61 
    62                  converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数
    63                          $.ajax({
    64                               accepts: {
    65                                 mycustomtype: 'application/x-some-custom-type'
    66                               },
    67 
    68                               // Expect a `mycustomtype` back from server
    69                               dataType: 'mycustomtype'
    70 
    71                               // Instructions for how to deserialize a `mycustomtype`
    72                               converters: {
    73                                 'text mycustomtype': function(result) {
    74                                   // Do Stuff
    75                                   return newresult;
    76                                 }
    77                               },
    78                             });
    View Code
    基于jQueryAjax - Demo
     1 <!DOCTYPE html>
     2     <html>
     3     <head lang="en">
     4         <meta charset="UTF-8">
     5         <title></title>
     6     </head>
     7     <body>
     8 
     9         <p>
    10             <input type="button" onclick="XmlSendRequest();" value='Ajax请求' />
    11         </p>
    12 
    13 
    14         <script type="text/javascript" src="jquery-1.12.4.js"></script>
    15         <script>
    16 
    17             function JqSendRequest(){
    18                 $.ajax({
    19                     url: "http://c2.com:8000/test/",
    20                     type: 'GET',
    21                     dataType: 'text',
    22                     success: function(data, statusText, xmlHttpRequest){
    23                         console.log(data);
    24                     }
    25                 })
    26             }
    27 
    28 
    29         </script>
    30     </body>
    31     </html>
    View Code

    图片验证码 + Session

    check_code.py

      1 #!/usr/bin/env python
      2 # -*- coding:utf-8 -*-
      3 
      4 import random
      5 from PIL import Image, ImageDraw, ImageFont, ImageFilter
      6 
      7 _letter_cases = "abcdefghjkmnpqrstuvwxy"  # 小写字母,去除可能干扰的i,l,o,z
      8 _upper_cases = _letter_cases.upper()  # 大写字母
      9 _numbers = ''.join(map(str, range(3, 10)))  # 数字
     10 init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
     11 
     12 
     13 def create_validate_code(size=(120, 30),
     14                          chars=init_chars,
     15                          img_type="GIF",
     16                          mode="RGB",
     17                          bg_color=(255, 255, 255),
     18                          fg_color=(0, 0, 255),
     19                          font_size=18,
     20                          font_type="Monaco.ttf",
     21                          length=4,
     22                          draw_lines=True,
     23                          n_line=(1, 2),
     24                          draw_points=True,
     25                          point_chance=2):
     26     """
     27     @todo: 生成验证码图片
     28     @param size: 图片的大小,格式(宽,高),默认为(120, 30)
     29     @param chars: 允许的字符集合,格式字符串
     30     @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
     31     @param mode: 图片模式,默认为RGB
     32     @param bg_color: 背景颜色,默认为白色
     33     @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
     34     @param font_size: 验证码字体大小
     35     @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
     36     @param length: 验证码字符个数
     37     @param draw_lines: 是否划干扰线
     38     @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
     39     @param draw_points: 是否画干扰点
     40     @param point_chance: 干扰点出现的概率,大小范围[0, 100]
     41     @return: [0]: PIL Image实例
     42     @return: [1]: 验证码图片中的字符串
     43     """
     44 
     45     width, height = size  # 宽高
     46     # 创建图形
     47     img = Image.new(mode, size, bg_color)
     48     draw = ImageDraw.Draw(img)  # 创建画笔
     49 
     50     def get_chars():
     51         """生成给定长度的字符串,返回列表格式"""
     52         return random.sample(chars, length)
     53 
     54     def create_lines():
     55         """绘制干扰线"""
     56         line_num = random.randint(*n_line)  # 干扰线条数
     57 
     58         for i in range(line_num):
     59             # 起始点
     60             begin = (random.randint(0, size[0]), random.randint(0, size[1]))
     61             # 结束点
     62             end = (random.randint(0, size[0]), random.randint(0, size[1]))
     63             draw.line([begin, end], fill=(0, 0, 0))
     64 
     65     def create_points():
     66         """绘制干扰点"""
     67         chance = min(100, max(0, int(point_chance)))  # 大小限制在[0, 100]
     68 
     69         for w in range(width):
     70             for h in range(height):
     71                 tmp = random.randint(0, 100)
     72                 if tmp > 100 - chance:
     73                     draw.point((w, h), fill=(0, 0, 0))
     74 
     75     def create_strs():
     76         """绘制验证码字符"""
     77         c_chars = get_chars()
     78         strs = ' %s ' % ' '.join(c_chars)  # 每个字符前后以空格隔开
     79 
     80         font = ImageFont.truetype(font_type, font_size)
     81         font_width, font_height = font.getsize(strs)
     82 
     83         draw.text(((width - font_width) / 3, (height - font_height) / 3),
     84                   strs, font=font, fill=fg_color)
     85 
     86         return ''.join(c_chars)
     87 
     88     if draw_lines:
     89         create_lines()
     90     if draw_points:
     91         create_points()
     92     strs = create_strs()
     93 
     94     # 图形扭曲参数
     95     params = [1 - float(random.randint(1, 2)) / 100,
     96               0,
     97               0,
     98               0,
     99               1 - float(random.randint(1, 10)) / 100,
    100               float(random.randint(1, 2)) / 500,
    101               0.001,
    102               float(random.randint(1, 2)) / 500
    103               ]
    104     img = img.transform(size, Image.PERSPECTIVE, params)  # 创建扭曲
    105 
    106     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜,边界加强(阈值更大)
    107 
    108     return img, strs
    View Code




  • 相关阅读:
    Java 动态编译
    在ubuntu 18.04下,无线网卡无驱动,连不上wifi,显示wifi没有适配器的解决方法
    由浅入深了解Thrift(1,2,3)
    Docker系列05:docker镜像制作 &Docker file
    Docker系列04:docker数据存储
    Docker系列03:docker网络
    关于在github上 下载源码 clone 非 master 分支的代码
    CentOS 6 & 7 忘记root密码的修改方法
    Windows RDP远程连接CentOS 7
    Windows 上用IntelliJ Idea调试百度大数据分析框架Apache Doris FE
  • 原文地址:https://www.cnblogs.com/uge3/p/7464761.html
Copyright © 2011-2022 走看看