AJAX(Asynchronous Javascript And XML)「異步Javascript和XML」。即便用Javascript語言與服務器進行異步交互,傳輸的數據爲XML(如今更多使用json數據)。javascript
AJAX除了異步的特色外,還有一個就是:瀏覽器頁面局部刷新;(這一特色給用戶的感覺是在不知不覺中完成請求和響應過程)css
ajax項目:html
1.用戶進入首頁,能夠點擊註冊和登陸前端
2.註冊頁,當輸入框失去焦點的時候校驗輸入的用戶名或者手機號存在,存在的話,給出相應提示vue
3.註冊,失敗給出相應提示,成功後臺將用戶數據寫入數據庫,前端跳轉至首頁java
4.登陸,登陸失敗給出相應提示,成功後跳轉至首頁python
5.實現文件的上傳mysql
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.htmljquery
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.htmlweb
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 %}
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 });
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()