PYTHON3.day01_Ajax

AJAX

1.什么是AJAX (阿贾克斯)
     Asynchronous Javascript And Xml
     异步的       JS         和  Xml (JSON)

    异步访问:
         当客户端向服务器端发送请求时,服务器在处理的过程中,客户端无需等待,可以做其他操作

    AJAX的优点:
         1.异步 的 访问方式
         2.局部 的 刷新方式
    
     使用场合:
         1.搜索建议
         2.表单验证
         3.前后端完全分离
             SPA -> Single Page Application
2.AJAX核心对象-异步对象(XMLHttpRequest)
     1.什么XMLHttpRequest
         简称为 "xhr"
         称为 "异步对象",代替浏览器向服务器发送异步的请求并接受响应
     2.创建异步对象
         xhr的创建是由js来提供的
         主流的异步对象是XMLHttpRequest类型的,并且主流浏览器都支持(IE7+,Chrome,Firefox,Safari,Opera)

        支持XMLHttpRequest:
             通过 new XMLHttpRequest()

        不支持XMLHttpRequet:
             通过new ActiveXObject("Microsoft.XMLHTTP")

        判断浏览器的支持性:
             if(window.XMLHttpRequest){
                 则说明浏览器支持 XMLHttpRequest
             }else{
                 则说明浏览器支持 ActiveXObject("...")
             }
        
         练习1:创建异步对象并输出
             1.创建一个Django程序 - AjaxDemo01
             2.创建一个应用 - ajax
             3.创建路由/视图
             4.在网页/模板中创建一个JS函数 - createXhr
             5.在函数中,创建异步对象并返回(或输出)
                 浏览器到底支持XMLHttpRequest还是ActiveXObject
3.XHR的成员
     1.方法 - open()
         作用:创建请求
         语法:xhr.open(method,url,async);
             method:请求方式,取值 'get' 或 'post'
             url:请求地址,取值 字符串
             async:是否采用异步的方式发送请求
                 true:异步的
                 false:同步的
             示例:使用get方式向02-server的地址发送异步请求
                 xhr.open('get','/02-server',true);
     2.属性 - readyState
         作用:表示请求状态,通过不同的请求状态值来表示xhr与服务器的交互情况
             由0-4共5个值来表示5个不同的状态
             0:请求尚未初始化
             1:已经与服务器建立连接
             2:服务器端已经接收请求信息
             3:服务器端处理中...
             4:响应完成
     3.属性 - status
         作用:表示服务器端的响应状态码
             200 : 服务器端正确处理请求并给出响应
             404 : Not Found
             500 : Internal Server Error

        示例:
             if(xhr.readyState==4 && xhr.status==200){
                 //可以接收服务器端的响应信息
             }
     4.属性 - responseText
         作用:表示服务器端响应回来的数据
         示例:
             if(xhr.readyState==4 && xhr.status==200){
                 //可以接收服务器端的响应信息
                 console.log(xhr.responseText);
             }
     5.事件 - onreadystatechange
         作用:每当xhr的readyState值发生改变时要触发的操作 - 回调函数
         示例:
             xhr.onreadystatechange = function(){
                     if(xhr.readyState==4 && xhr.status==200){
                     //可以接收服务器端的响应信息
                     console.log(xhr.responseText);
                 }
             }
     6.方法 - send()
         作用:通知xhr向服务器端开始发送请求
         语法:xhr.send(body);
             body:请求主体
             get请求:body的值为null
                 xhr.send(null);
             post请求:body的置为 具体的请求数据
                 xhr.send("请求数据");
4.AJAX的操作步骤
     1.GET请求
         1.创建 xhr
         2.创建请求 - open()
         3.设置回调函数 - onreadystatechange
             1.判断状态
             2.接收响应
             3.业务处理
         4.发送请求 - send(null)
/02-server?uname=wangwc&uage=30

2019-07-24_19-38-09

  1 """
  2 Django settings for AjaxDemo01 project.
  3 
  4 Generated by 'django-admin startproject' using Django 1.11.8.
  5 
  6 For more information on this file, see
  7 https://docs.djangoproject.com/en/1.11/topics/settings/
  8 
  9 For the full list of settings and their values, see
 10 https://docs.djangoproject.com/en/1.11/ref/settings/
 11 """
 12 
 13 import os
 14 
 15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 17 
 18 # Quick-start development settings - unsuitable for production
 19 # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
 20 
 21 # SECURITY WARNING: keep the secret key used in production secret!
 22 SECRET_KEY = 'bxn_hxqst@2p=es9ig6+zx0s32am#fo%-pako(qh5li^4hc+wj'
 23 
 24 # SECURITY WARNING: don't run with debug turned on in production!
 25 DEBUG = True
 26 
 27 ALLOWED_HOSTS = []
 28 
 29 # Application definition
 30 
 31 INSTALLED_APPS = [
 32   'django.contrib.admin',
 33   'django.contrib.auth',
 34   'django.contrib.contenttypes',
 35   'django.contrib.sessions',
 36   'django.contrib.messages',
 37   'django.contrib.staticfiles',
 38   'ajax',
 39 ]
 40 
 41 MIDDLEWARE = [
 42   'django.middleware.security.SecurityMiddleware',
 43   'django.contrib.sessions.middleware.SessionMiddleware',
 44   'django.middleware.common.CommonMiddleware',
 45   'django.middleware.csrf.CsrfViewMiddleware',
 46   'django.contrib.auth.middleware.AuthenticationMiddleware',
 47   'django.contrib.messages.middleware.MessageMiddleware',
 48   'django.middleware.clickjacking.XFrameOptionsMiddleware',
 49 ]
 50 
 51 ROOT_URLCONF = 'AjaxDemo01.urls'
 52 
 53 TEMPLATES = [
 54   {
 55     'BACKEND': 'django.template.backends.django.DjangoTemplates',
 56     'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
 57     'APP_DIRS': True,
 58     'OPTIONS': {
 59       'context_processors': [
 60         'django.template.context_processors.debug',
 61         'django.template.context_processors.request',
 62         'django.contrib.auth.context_processors.auth',
 63         'django.contrib.messages.context_processors.messages',
 64       ],
 65     },
 66   },
 67 ]
 68 
 69 WSGI_APPLICATION = 'AjaxDemo01.wsgi.application'
 70 
 71 # Database
 72 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
 73 
 74 DATABASES = {
 75   'default': {
 76     'ENGINE': 'django.db.backends.mysql',
 77     'NAME': 'ajaxDB',
 78     'USER': 'root',
 79     'PASSWORD': '123456',
 80     'HOST': 'localhost',
 81     'PORT': 3306
 82   }
 83 }
 84 
 85 # Password validation
 86 # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
 87 
 88 AUTH_PASSWORD_VALIDATORS = [
 89   {
 90     'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
 91   },
 92   {
 93     'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
 94   },
 95   {
 96     'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
 97   },
 98   {
 99     'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
100   },
101 ]
102 
103 # Internationalization
104 # https://docs.djangoproject.com/en/1.11/topics/i18n/
105 
106 LANGUAGE_CODE = 'en-us'
107 
108 TIME_ZONE = 'UTC'
109 
110 USE_I18N = True
111 
112 USE_L10N = True
113 
114 USE_TZ = True
115 
116 # Static files (CSS, JavaScript, Images)
117 # https://docs.djangoproject.com/en/1.11/howto/static-files/
118 
119 # 配置访问路径
120 STATIC_URL = '/static/'
121 # 配置存储路径
122 STATICFILES_DIRS = [
123   os.path.join(BASE_DIR, 'static'),
124 ]
125 
settings.py
  1 from django.conf.urls import url,include
  2 from django.contrib import admin
  3 
  4 urlpatterns = [
  5     url(r'^admin/', admin.site.urls),
  6     url(r'^ajax/',include('ajax.urls')),
  7 ]
  8 
AjaxDemo01_urls.py
  1 from django.db import models
  2 
  3 # Create your models here.
  4 class Users(models.Model):
  5   uname = models.CharField("用户名称",max_length=30)
  6   upwd = models.CharField("用户密码",max_length=30)
  7   uemail = models.EmailField("电子邮箱")
  8   nickname = models.CharField("用户昵称",max_length=30)
  9 
ajax_models.py
  1 from django.conf.urls import url
  2 from . import views
  3 
  4 urlpatterns = [
  5   # 1. 演示创建xhr
  6   url(r'^01-createxhr/$', views.create_views),
  7   # 2. 演示使用ajax发送get请求的步骤
  8   url(r'^02-server/$', views.server02_views),
  9   url(r'^02-ajax-get/$', views.ajaxget_views),
 10   # 3. 演示使用ajax发送get请求并附带参数
 11   url(r'^03-ajax-get-params/$', views.getparams_views),
 12   url(r'^03-server/$', views.server03_views),
 13   # 4. 使用 AJAX 完成注册操作
 14   url(r'^04-register/$',views.register_views),
 15   url(r'^04-checkuname/$',views.checkuname_views),
 16 ]
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
ajax_urls.py
  1 from django.http import HttpResponse
  2 from django.shortcuts import render
  3 
  4 # Create your views here.
  5 from ajax.models import Users
  6 
  7 
  8 def create_views(request):
  9     return render(request,'01-createxhr.html')
 10 
 11 def server02_views(request):
 12     return HttpResponse("这是server02的响应内容")
 13 
 14 def ajaxget_views(request):
 15     return render(request,'02-ajax-get.html')
 16 
 17 def getparams_views(request):
 18     return render(request,'03-ajax-get-params.html')
 19 
 20 def server03_views(request):
 21     #1. 接收前端传递过来的两个参数
 22     name = request.GET['name']
 23     age = request.GET['age']
 24     #2. 响应数据给前端
 25     s = "姓名:%s,年龄:%s" % (name,age)
 26     return HttpResponse(s)
 27 
 28 def register_views(request):
 29   return render(request,'04-register.html')
 30 
 31 def checkuname_views(request):
 32   # 1.接收前端传递过来的参数 - uname
 33   uname = request.GET['uname']
 34   # 2.判断uname在Users实体中是否存在[查询操作]
 35   users = Users.objects.filter(uname=uname)
 36   # 3.根据查询结果给出响应
 37   if users:
 38     return HttpResponse("1")
 39   return HttpResponse("0")
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
ajax_views.py
  1 function createXhr(){
  2     var xhr = null;
  3     //根据不同的浏览器创建不同的异步对象
  4     if(window.XMLHttpRequest){
  5       xhr = new XMLHttpRequest();
  6     }else{
  7       xhr = new ActiveXObject("Microsoft.XMLHTTP");
  8     }
  9     return xhr;
 10 }
common.js
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <script>
  7 
  8     </script>
  9 </head>
 10 <body>
 11     <button onclick="createXhr()">创建XHR</button>
 12 </body>
 13 </html>
createxhr.html
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <script src="/static/common.js"></script>
  7     <script>
  8         function btnShow(){
  9             //1.创建xhr
 10             var xhr = createXhr();
 11             //2.创建请求
 12             xhr.open("get","/ajax/02-server",true);
 13             //3.设置回调函数
 14             xhr.onreadystatechange = function(){
 15                 if(xhr.readyState==4 && xhr.status==200){
 16                     //接收服务器端响应的数据
 17                     var res = xhr.responseText;
 18                     document.getElementById("show").innerHTML = res;
 19                 }
 20             }
 21             //4.发送请求
 22             xhr.send(null);
 23         }
 24     </script>
 25 </head>
 26 <body>
 27     <button onclick="btnShow()">显示</button>
 28     <a href="/ajax/02-server">显示</a>
 29     <div id="show"></div>
 30 </body>
 31 </html>
02-ajaxget.html
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4   <meta charset="UTF-8">
  5   <title>Title</title>
  6   <script src="/static/common.js"></script>
  7   <script>
  8         function btnShow(){
  9             //1.创建xhr
 10             var xhr = createXhr();
 11             //2.创建请求(带参数)
 12             var url = "/ajax/03-server?name=wangwc&age=30";
 13             xhr.open("get",url,true);
 14             //3.设置回调函数
 15             xhr.onreadystatechange = function(){
 16                 if(xhr.readyState==4&&xhr.status==200){
 17                     document.getElementById("show").innerHTML = xhr.responseText;
 18                 }
 19             }
 20             //4.发送请求
 21             xhr.send(null);
 22         }
 23 
 24 
 25 
 26   </script>
 27 
 28 </head>
 29 <body>
 30 <button onclick="btnShow()">显示</button>
 31 <div id="show"></div>
 32 </body>
 33 </html>
03-ajax-get-params.html
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4   <meta charset="UTF-8">
  5   <title>Title</title>
  6   <script src="/static/common.js"></script>
  7   <script src="/static/jquery-1.11.3.js"></script>
  8   <script>
  9     $(function(){
 10       /**
 11        * 为 #uname 绑定 blur 事件
 12        */
 13        $("#uname").blur(function(){
 14           //1.创建xhr
 15           var xhr = createXhr();
 16           //2.创建请求 - /ajax/04-checkuname
 17           var uname = $("#uname").val();
 18           var url = "/ajax/04-checkuname?uname="+uname;
 19           xhr.open("get",url,true);
 20           //3.设置回调函数
 21           xhr.onreadystatechange = function(){
 22             if(xhr.readyState==4 && xhr.status==200){
 23               //$("#uname-tip").html(xhr.responseText);
 24               if(xhr.responseText == "1"){
 25                 $("#uname-tip").html("用户名称已经存在");
 26               }else{
 27                 $("#uname-tip").html("通过");
 28               }
 29             }
 30           }
 31           //4.发送请求
 32           xhr.send(null);
 33        });
 34     });
 35   </script>
 36 </head>
 37 <body>
 38   <div>
 39     <p>
 40       用户名称:<input type="text" id="uname">
 41       <span id="uname-tip"></span>
 42     </p>
 43     <p>
 44       用户密码:<input type="password" id="upwd">
 45     </p>
 46     <p>
 47       电子邮箱:<input type="email" id="uemail">
 48     </p>
 49     <p>
 50       用户昵称: <input type="text" id="nickname">
 51     </p>
 52     <p>
 53       <input type="button" value="注册">
 54     </p>
 55   </div>
 56 </body>
 57 </html>
04-register.html
原文地址:https://www.cnblogs.com/shengjia/p/11240465.html