django_ajax
AJAX(Asynchronous Javascript And XML)“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(现在更多使用json数据)。
- 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
- 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)
优点:
- AJAX使用Javascript技术向服务器发送异步请求
- AJAX无须刷新整个页面
ajax项目:
1.用户进入首页,可以点击注册和登录
2.注册页,当输入框失去焦点的时候校验输入的用户名或者手机号存在,存在的话,给出相应提示
3.注册,失败给出相应提示,成功后台将用户数据写入数据库,前端跳转至首页
4.登录,登录失败给出相应提示,成功后跳转至首页
5.实现文件的上传



HTML代码

1 <div class="action"> 2 <div class="panel panel-danger"> 3 <div class="panel-heading">2019进击的菜鸟</div> 4 <div class="panel-body"> 5 web框架开发 6 </div> 7 <div class="panel-body"> 8 crm&爬虫 9 </div> 10 <div class="panel-body"> 11 算法&设计模式&企业应用 12 </div> 13 <div class="panel-body"> 14 vue项目 15 </div> 16 <div class="panel-body"> 17 复习python&自动化&性能 18 </div> 19 </div> 20 <div class="panel panel-warning"> 21 <div class="panel-heading">2020进击的小鸟</div> 22 <div class="panel-body"> 23 fighting! 24 </div> 25 </div> 26 <div class="panel panel-success"> 27 <div class="panel-heading">2021进击的大鸟</div> 28 <div class="panel-body"> 29 go on ! 30 </div> 31 </div> 32 </div>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block title %}
<title>base——title</title>
{% endblock title %}
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
{% block style %}
<style type="text/css">
*{
padding: 0;
margin:0;
}
.header{
width:100%;
height: 50px;
background-color: #369;
}
body{
background:#FFF url('/static/base.jpg') repeat-x 0;
background-attachment: fixed;
}
</style>
{% endblock style %}
</head>
<body>
<div class="header"></div>
<div class="container">
<div class="row">
<div class="col-md-3">
{% include 'advertise.html' %}
</div>
<div class="col-md-6">
{% block content%}
<h3>base_content</h3>
{% endblock %}
</div>
</div>
</div>
</body>
{% block js %}
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
{% endblock js %}
</html>

1 {% extends 'base.html' %}
2
3
4 {% block title %}
5 <title>index</title>
6 {% endblock title %}
7
8 {% block style %}
9 {{ block.super }}
10 <style>
11 img{
12 margin: 20px auto;
13 }
14 .btn{
15 margin-right: 20px;
16 }
17 </style>
18 {% endblock style %}
19
20 {% block content %}
21 <h3>欢迎进入首页 {{ word }}</h3>
22 <a href="/app01/regist" class="btn btn-info">注册</a>
23 <a href="/app01/login" class="btn btn-info">登陆</a>
24 <form action="">
25 <img src="/static/index.jpg">
26 </form>
27 {% endblock content %}
module6/07 django与ajax/ajax/templates/login.html
1 {% extends 'base.html' %}
2
3
4 {% block title %}
5 <title>index</title>
6 {% endblock title %}
7
8 {% block style %}
9 {{ block.super }}
10 <style>
11 .regist {
12 margin: 20px auto;
13 }
14 .res {
15 margin: 20px auto;
16 font-size: 18px;
17 color: red;
18 }
19 </style>
20 {% endblock style %}
21
22 {% block content %}
23 <h3>登陆页面</h3>
24 <hr>
25 <div class="regist">
26 <form>
27 <div class="form-group">
28 <label for="">用户名</label>
29 <input type="text" class="form-control" id="name" placeholder="Name">
30 </div>
31 <div class="form-group">
32 <label for="">密码</label>
33 <input type="password" class="form-control" id="pwd" placeholder="Password">
34 </div>
35 <button type="submit" class="btn btn-success" id="btn">登陆</button>
36 <p class="res"></p>
37 </form>
38 </div>
39 {% endblock content %}
40
41 {% block js %}
42 {{ block.super }}
43 <script type="text/javascript" src="/static/login.js"></script>
44 {% endblock js %}
module6/07 django与ajax/ajax/templates/regist.html
1 {% extends 'base.html' %}
2
3
4 {% block title %}
5 <title>index</title>
6 {% endblock title %}
7
8 {% block style %}
9 {{ block.super }}
10 <style>
11 .regist {
12 margin: 20px auto;
13 }
14 .res{
15 margin: 20px auto;
16 font-size: 18px;
17 }
18 .success{
19 color:green;
20 }
21 .error{
22 color: red;
23 }
24 .check{
25 color: red;
26 float: right;
27 }
28 </style>
29 {% endblock style %}
30
31 {% block content %}
32 <h3>注册页面</h3>
33 <hr>
34 <div class="regist">
35 <form>
36 <div class="form-group">
37 <label for="">用户名</label>
38 <input type="text" class="form-control" id="name" placeholder="Name">
39 <span class="check"></span>
40 </div>
41 <div class="form-group">
42 <label for="">昵称</label>
43 <input type="text" class="form-control" id="nickname" placeholder="Nickname">
44 <span class="check"></span>
45 </div>
46 <div class="form-group">
47 <label for="">手机号</label>
48 <input type="text" class="form-control" id="phone" placeholder="Phone_no">
49 <span class="check"></span>
50 </div>
51 <div class="form-group">
52 <label for="">密码</label>
53 <input type="password" class="form-control" id="pwd" placeholder="Password">
54 </div>
55 <div class="form-group">
56 <label for="">确认密码</label>
57 <input type="password" class="form-control" id="confirm_pwd" placeholder="ConfirmPassword">
58 </div>
59 <button type="submit" class="btn btn-success" id="btn">注册</button>
60 <p class="res"></p>
61 </form>
62 </div>
63 {% endblock content %}
64
65 {% block js %}
66 {{ block.super }}
67 <script type="text/javascript" src="/static/regist.js"></script>
68 {% endblock js %}
module6/07 django与ajax/ajax/templates/file.html
1 {% extends 'base.html' %}
2
3
4 {% block title %}
5 <title>文件</title>
6 {% endblock title %}
7
8 {% block style %}
9 {{ block.super }}
10 <style>
11 .file{
12 margin:20px auto;
13 }
14 </style>
15 {% endblock style %}
16
17
18 {% block content %}
19 <div class="file">
20 {# 默认是form表单类型 enctype="application/x-www-form-urlencoded" 传参为 a=1&b=2&c=3 #}
21 {# 上传文件必须要指定类型 enctype="multipart/form-data" 否则不会上传文件,ajax没有这个限制 #}
22 <form action="" method="post" enctype="multipart/form-data">
23 <div class="form-group">
24 <label for="">用户名</label>
25 <input type="text" class="form-control" id="fileform" placeholder="Name" name="name">
26 </div>
27 <div class="form-group">
28 <label for="">form表单传头像</label>
29 <input type="file" id="form_file" name="imgfile">
30 </div>
31 <button type="submit" class="btn btn-success" id="form_btn">提交</button>
32 </form>
33 </div>
34 <hr>
35 <div class="file">
36 <form action="" >
37 <div class="form-group">
38 <label for="">用户名</label>
39 <input type="text" class="form-control" id="fileajax" placeholder="Name">
40 </div>
41 <div class="form-group">
42 <label for="">ajax传头像</label>
43 <input type="file" id="ajax_file">
44 </div>
45 <button type="submit" class="btn btn-success" id="ajax_btn">提交</button>
46 </form>
47 </div>
48 {% endblock content %}
49
50 {% block js %}
51 {{ block.super }}
52 <script src="/static/file.js"></script>
53 {% endblock js %}
JS代码
jquery自行下载
module6/07 django与ajax/ajax/statics/login.js
1 $(function () {
2 $('#btn').click(function (e) {
3 e.preventDefault();
4 // var formdata = new FormData(); 表单数据不可以用 FormData 文件才可以
5 var data = {};
6 data.name = $('#name').val().trim();
7 data.pwd = $('#pwd').val().trim();
8 if (data.name && data.pwd) {
9 $.ajax({
10 url: '',
11 type: 'post',
12 data: data, // ajax默认application/x-www-form-urlencoded格式
13 success: function (data) {
14 data = JSON.parse(data);
15 if (data.user) {
16 location.href = '/app01/index'
17 } else {
18 $('.res').html(data.msg)
19 }
20 }
21 })
22 } else {
23 alert("用户名或密码不能为空!")
24 }
25 })
26
27 });
module6/07 django与ajax/ajax/statics/regist.js
1 $(function () {
2 // 鼠标失去焦点校验字符是否已存在
3 check_obj = $('input[type="text"]');
4 for (var i = 0; i < check_obj.length; i++) {
5 $(check_obj[i]).focus(function () {
6 $(this).next().text('');
7 });
8 $(check_obj[i]).blur(function () {
9 data_dic = {};
10 data_dic.type = this.id;
11 data_dic.value = this.value;
12 $.ajax({
13 url: '/app01/check/',
14 type: 'post',
15 contentType:"application/json",
16 data: JSON.stringify(data_dic),
17 success: function (data) {
18 var data_json = JSON.parse(data);
19 console.log(data_json);
20 if (data_json['code'] !== '000000') {
21 type_id = '#' + data_dic.type;
22 $(type_id).next().html(data_json['msg']);
23 console.log(data_json);
24 }
25 },
26 error: function (err) {
27 console.log(err)
28 }
29 })
30 });
31 }
32
33 // 注册逻辑
34 $('#btn').click(function (e) {
35 e.preventDefault();
36 name = $('#name').val().trim();
37 nickname = $('#nickname').val().trim();
38 phone = $('#phone').val().trim();
39 pwd = $('#pwd').val().trim();
40 confirm_pwd = $('#confirm_pwd').val().trim();
41 if (name && pwd && confirm_pwd && pwd === confirm_pwd) {
42 var mydata = {};
43 mydata.name = name;
44 mydata.nickname = nickname;
45 mydata.phone = phone;
46 mydata.pwd = pwd;
47 mydata.confirm_pwd = confirm_pwd;
48 $.ajax({
49 url: '',
50 type: 'post',
51 data: mydata,
52 success: function (data) {
53 var data_json = JSON.parse(data);
54 if (data_json['code'] === '000000') {
55 $('.res').addClass('success').html(data_json['msg']);
56 location.href = '/app01/index'
57 } else {
58 $('.res').addClass('error').html(data_json['msg'])
59 }
60 },
61 error: function (err) {
62 console.log(err)
63 }
64 })
65 } else {
66 alert('用户名和密码不能为空,且密码与确认密码一致!')
67 }
68 });
69 });
module6/07 django与ajax/ajax/statics/file.js
1 $('#ajax_btn').click(function (e) {
2 e.preventDefault();
3 // 同form表单文件请求一样,原默认的 application/x-www-form-urlencoded 类型不支持文件上传,需要转换请求参数类型
4 // 文件必须要以 FormData 数据类型传递
5 var formdata = new FormData();
6 formdata.append('name', $('#fileajax').val());
7 formdata.append('imgfile', $('#ajax_file')[0].files[0]);
8 $.ajax({
9 url: '',
10 type: 'post',
11 data: formdata,
12 // 传FormData时 必须设置下面两个参数,不给参数,会报错(js非法输入)
13 processData: false, // 不处理数据,让FormData自己去处理数据
14 contentType: false, // 不设置内容类型,让FormData自己设置内容类型
15 success: function (data) {
16 console.log(data)
17 }
18 })
19 });
应用app代码

from django.urls import path, re_path
from ajax_app01 import views
urlpatterns = [
path('index/', views.index),
path('login/', views.login),
path('regist/', views.regist),
path('check/', views.check),
path('file/', views.file),
]

1 from django.db import models 2 3 # Create your models here. 4 5 6 class UserDetail(models.Model): 7 id = models.AutoField(primary_key=True) 8 nickname = models.CharField(max_length=32) 9 phone = models.BigIntegerField(null=True) 10 age = models.BigIntegerField(null=True) 11 address = models.CharField(max_length=32,null=True) 12 dep = models.CharField(max_length=32,null=True) 13 14 15 class UserInfo(models.Model): 16 id = models.AutoField(primary_key=True) 17 name = models.CharField(max_length=16) 18 password = models.CharField(max_length=16) 19 user_detail = models.OneToOneField(to=UserDetail, on_delete=models.CASCADE)
module6/07 django与ajax/ajax/ajax_app01/views.py
1 from django.shortcuts import render, HttpResponse
2 from ajax_app01.models import *
3 from django.db.models import Q
4 import json
5
6 # Create your views here.
7
8
9 def regist(request):
10 method = request.method
11 if method == 'POST':
12 name = request.POST.get('name')
13 pwd = request.POST.get('pwd')
14 nickname = request.POST.get('nickname')
15 phone = request.POST.get('phone')
16 select_res = UserInfo.objects.filter(Q(name=name)|Q(user_detail__nickname=nickname)).exists()
17 res = {"code":None,"msg":None}
18 if select_res:
19 res["code"]="100000"
20 res["msg"]="用户已存在!"
21 else:
22 detail = UserDetail.objects.create(nickname=nickname, phone=phone)
23 UserInfo.objects.create(name=name, password=pwd, user_detail=detail)
24 res["code"] = "000000"
25 res["msg"] = "注册成功!"
26 return HttpResponse(json.dumps(res))
27 else:
28 return render(request, 'regist.html')
29
30
31 def index(request):
32 return render(request, 'index.html')
33
34
35 def login(request):
36 if request.method == 'POST':
37 name = request.POST.get('name')
38 pwd = request.POST.get('pwd')
39 select_res = UserInfo.objects.filter(name=name,password=pwd).exists()
40 res = {"user":None,"msg":None}
41 if select_res:
42 res["user"] = name
43 else:
44 res["msg"] = "用户名或密码错误!"
45 return HttpResponse(json.dumps(res))
46 return render(request, 'login.html')
47
48
49 def check(request):
50 method = request.method
51 if method == 'POST':
52 dic = {'name':'用户名','nickname':'用户昵称','phone':'手机号'}
53 print(request.body) # 原始的请求体数据 不管啥类型的请求数据都取的到
54 print(request.POST) # POST请求数据 if contentType==urlencoded ,request.POST才有数据
55 req_data = json.loads(request.body.decode('utf8'))
56 type = req_data['type']
57 value = req_data['value']
58 if type == 'name':
59 res = UserInfo.objects.filter(name=value).exists()
60 elif type == 'nickname':
61 res = UserInfo.objects.filter(user_detail__nickname=value).exists()
62 else:
63 res = UserInfo.objects.filter(user_detail__phone=value).exists()
64 if res:
65 return HttpResponse('{"code":"100000","msg":"%s已存在!"}'%dic[type])
66 else:
67 return HttpResponse('{"code":"000000","msg":"校验成功!"}')
68 else:
69 return render(request, 'index.html')
70
71
72 def file(request):
73 import os
74 from ajax.settings import STATICFILES_DIRS
75 if request.method == 'POST':
76 if request.is_ajax():
77 print('--------------------------ajax--------------------------')
78 print(request.body) # 原始的请求体数据
79 print(request.GET) # GET请求数据
80 print(request.POST) # POST请求数据 if contentType==urlencoded ,request.POST才有数据
81 print(request.FILES) # 上传的文件数据
82 file_obj = request.FILES.get('imgfile')
83 with open(os.path.join(STATICFILES_DIRS[0],file_obj.name), 'wb') as f:
84 for line in file_obj:
85 f.write(line)
86 else:
87 print('--------------------------form--------------------------')
88 print(request.body) # 原始的请求体数据
89 print(request.GET) # GET请求数据
90 print(request.POST) # POST请求数据 if contentType==urlencoded ,request.POST才有数据
91 print(request.FILES) # 上传的文件数据
92 file_obj = request.FILES.get('imgfile')
93 with open(os.path.join(STATICFILES_DIRS[0],file_obj.name), 'wb') as f:
94 for line in file_obj:
95 f.write(line)
96 return HttpResponse('OJBK!')
97 return render(request, 'file.html')
项目代码

"""
Django settings for ajax project.
Generated by 'django-admin startproject' using Django 2.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#2jnwyw8s+e-va299kxg7iv#+7weu#d(@i610-f5cxrvqmx%&e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ajax_app01',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ajax.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ajax.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'statics')
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'ajax',# 要连接的数据库,连接前需要创建好
'USER':'root',# 连接数据库的用户名
'PASSWORD':'root',# 连接数据库的密码
'HOST':'127.0.0.1',# 连接主机,默认本级
'PORT':3306 # 端口 默认3306
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}

1 """ajax URL Configuration
2
3 The `urlpatterns` list routes URLs to views. For more information please see:
4 https://docs.djangoproject.com/en/2.2/topics/http/urls/
5 Examples:
6 Function views
7 1. Add an import: from my_app import views
8 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 Class-based views
10 1. Add an import: from other_app.views import Home
11 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 Including another URLconf
13 1. Import the include() function: from django.urls import include, path
14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 """
16 from django.contrib import admin
17 from django.urls import path, re_path, include
18
19 urlpatterns = [
20 path('admin/', admin.site.urls),
21 re_path(r'^app01/', include(('ajax_app01.urls','ajax_app01'))),
22 ]

import pymysql pymysql.install_as_MySQLdb()
