Django和Ajax
本文目錄
- 一 什么是Ajax
- 二 基于jquery的Ajax實現(xiàn)
- 三 案例
- 四 文件上傳
- 五 Ajax提交json格式數(shù)據(jù)
- 六 Django內(nèi)置的serializers(把對象序列化成json字符串)
- 七:Ajax登錄驗證
?
一 什么是Ajax
?
AJAX(Asynchronous Javascript And XML)翻譯成中文就是“異步Javascript和XML”。即使用Javascript語言與服務(wù)器進行異步交互,傳輸?shù)臄?shù)據(jù)為XML(當(dāng)然,傳輸?shù)臄?shù)據(jù)不只是XML,現(xiàn)在更多使用json數(shù)據(jù))。
?
- 同步交互:客戶端發(fā)出一個請求后,需要等待服務(wù)器響應(yīng)結(jié)束后,才能發(fā)出第二個請求;
- 異步交互:客戶端發(fā)出一個請求后,無需等待服務(wù)器響應(yīng)結(jié)束,就可以發(fā)出第二個請求。
?
AJAX除了異步的特點外,還有一個就是:瀏覽器頁面局部刷新;(這一特點給用戶的感受是在不知不覺中完成請求和響應(yīng)過程)
?
場景:
優(yōu)點:
- AJAX使用Javascript技術(shù)向服務(wù)器發(fā)送異步請求
- AJAX無須刷新整個頁面
二 基于jquery的Ajax實現(xiàn)
<button class="send_Ajax">send_Ajax</button> <script>$(".send_Ajax").click(function(){$.ajax({url:"/handle_Ajax/",type:"POST",data:{username:"Yuan",password:123},success:function(data){console.log(data)},error: function (jqXHR, textStatus, err) {console.log(arguments);},complete: function (jqXHR, textStatus) {console.log(textStatus);},statusCode: {'403': function (jqXHR, textStatus, err) {console.log(arguments);},'400': function (jqXHR, textStatus, err) {console.log(arguments);}}})})</script>Ajax---->服務(wù)器------>Ajax執(zhí)行流程圖
三 案例
一 通過Ajax,實現(xiàn)前端輸入兩個數(shù)字,服務(wù)器做加法,返回到前端頁面
def test_ajax(requests):n1=int(request.POST.get('n1'))n2=int(request.POST.get('n2'))return HttpResponse(n1+n2) 視圖函數(shù) $("#submit").click(function(){$.ajax({url:'test_ajax',type:'post',data:{n1:$('#num1').val(),n2:$('#num2').val()} success:$(function(data)){console.log(data)$("#sum").val(data)} }) }) js代碼 <input type="text" id="num1">+<input type="text" id="num2">=<input type="text" id="sum"> <button id="submit">計算</button> HTML代碼?
?二 基于Ajax進行登錄驗證
用戶在表單輸入用戶名與密碼,通過Ajax提交給服務(wù)器,服務(wù)器驗證后返回響應(yīng)信息,客戶端通過響應(yīng)信息確定是否登錄成功,成功,則跳轉(zhuǎn)到首頁,否則,在頁面上顯示相應(yīng)的錯誤信息
def auth(request):back_dic={'user':None,'message':None}name=request.POST.get('user')password=request.POST.get('password')print(name)print(password)user=models.user.objects.filter(name=name,password=password).first()print(user)# print(user.query)if user:back_dic['user']=user.nameback_dic['message']='成功'else:back_dic['message']='用戶名或密碼錯誤'import jsonreturn HttpResponse(json.dumps(back_dic)) 視圖函數(shù) $("#submit3").click(function () {$.ajax({url: '/auth/',type: 'post',data: {'user': $("#id_name").val(),'password': $('#id_password').val()},success: function (data) {{#console.log(data)#}var data=JSON.parse(data)if (data.user){location.href='https://www.baidu.com'}else {$(".error").html(data.message).css({'color':'red','margin-left':'20px'})}}})})Js代碼 JS代碼?
四 文件上傳
請求頭ContentType
1 application/x-www-form-urlencoded
這應(yīng)該是最常見的 POST 提交數(shù)據(jù)的方式了。瀏覽器的原生 <form> 表單,如果不設(shè)置?enctype?屬性,那么最終就會以 application/x-www-form-urlencoded 方式提交數(shù)據(jù)。請求類似于下面這樣(無關(guān)的請求頭在本文中都省略掉了):
POST http://www.example.com HTTP/1.1 Content-Type: application/x-www-form-urlencoded;charset=utf-8user=lqz&age=222 multipart/form-data
這又是一個常見的 POST 數(shù)據(jù)提交的方式。我們使用表單上傳文件時,必須讓 <form> 表單的?enctype?等于 multipart/form-data。直接來看一個請求示例:
POST http://www.example.com HTTP/1.1 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="user"yuan ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="file"; filename="chrome.png" Content-Type: image/pngPNG ... content of chrome.png ... ------WebKitFormBoundaryrGKCBY7qhFd3TrwA--這個例子稍微復(fù)雜點。首先生成了一個 boundary 用于分割不同的字段,為了避免與正文內(nèi)容重復(fù),boundary 很長很復(fù)雜。然后 Content-Type 里指明了數(shù)據(jù)是以 multipart/form-data 來編碼,本次請求的 boundary 是什么內(nèi)容。消息主體里按照字段個數(shù)又分為多個結(jié)構(gòu)類似的部分,每部分都是以?--boundary?開始,緊接著是內(nèi)容描述信息,然后是回車,最后是字段具體內(nèi)容(文本或二進制)。如果傳輸?shù)氖俏募?#xff0c;還要包含文件名和文件類型信息。消息主體最后以?--boundary--?標(biāo)示結(jié)束。關(guān)于 multipart/form-data 的詳細定義,請前往?rfc1867?查看。
這種方式一般用來上傳文件,各大服務(wù)端語言對它也有著良好的支持。
上面提到的這兩種 POST 數(shù)據(jù)的方式,都是瀏覽器原生支持的,而且現(xiàn)階段標(biāo)準(zhǔn)中原生 <form> 表單也只支持這兩種方式(通過 <form> 元素的?enctype?屬性指定,默認為?application/x-www-form-urlencoded。其實?enctype?還支持?text/plain,不過用得非常少)。
隨著越來越多的 Web 站點,尤其是 WebApp,全部使用 Ajax 進行數(shù)據(jù)交互之后,我們完全可以定義新的數(shù)據(jù)提交方式,給開發(fā)帶來更多便利。
3 application/json
application/json 這個 Content-Type 作為響應(yīng)頭大家肯定不陌生。實際上,現(xiàn)在越來越多的人把它作為請求頭,用來告訴服務(wù)端消息主體是序列化后的 JSON 字符串。由于 JSON 規(guī)范的流行,除了低版本 IE 之外的各大瀏覽器都原生支持 JSON.stringify,服務(wù)端語言也都有處理 JSON 的函數(shù),使用 JSON 不會遇上什么麻煩。
JSON 格式支持比鍵值對復(fù)雜得多的結(jié)構(gòu)化數(shù)據(jù),這一點也很有用。記得我?guī)啄昵白鲆粋€項目時,需要提交的數(shù)據(jù)層次非常深,我就是把數(shù)據(jù) JSON 序列化之后來提交的。不過當(dāng)時我是把 JSON 字符串作為 val,仍然放在鍵值對里,以 x-www-form-urlencoded 方式提交。
基于Form表單上傳文件
<form action="/file_put/" method="post" enctype="multipart/form-data">用戶名:<input type="text" name="name">頭像:<input type="file" name="avatar" id="avatar1"> <input type="submit" value="提交"> </form>必須指定?enctype="multipart/form-data"
視圖函數(shù):
def file_put(request):if request.method=='GET':return render(request,'file_put.html')else:# print(request.POST)# print(request.POST)print(request.body) # 原始的請求體數(shù)據(jù) print(request.GET) # GET請求數(shù)據(jù) print(request.POST) # POST請求數(shù)據(jù) print(request.FILES) # 上傳的文件數(shù)據(jù)# print(request.body.decode('utf-8'))print(request.body.decode('utf-8'))print(request.FILES)file_obj=request.FILES.get('avatar')print(type(file_obj))with open(file_obj.name,'wb') as f:for line in file_obj:f.write(line)return HttpResponse('ok')?
基于Ajax上傳文件
$("#ajax_button").click(function () {var formdata=new FormData()formdata.append('name',$("#id_name2").val())formdata.append('avatar',$("#avatar2")[0].files[0])$.ajax({url:'',type:'post',processData:false, //告訴jQuery不要去處理發(fā)送的數(shù)據(jù)contentType:false,// 告訴jQuery不要去設(shè)置Content-Type請求頭data:formdata,success:function (data) {console.log(data)}})})瀏覽器請求頭為:
Content-Type:?
multipart/form-data; boundary=----WebKitFormBoundaryA5O53SvUXJaF11O2五 Ajax提交json格式數(shù)據(jù)
$("#ajax_test").click(function () {var dic={'name':'lqz','age':18}$.ajax({url:'',type:'post',contentType:'application/json', //一定要指定格式 contentType: 'application/json;charset=utf-8',data:JSON.stringify(dic), //轉(zhuǎn)換成json字符串格式success:function (data) {console.log(data)}})})提交到服務(wù)器的數(shù)據(jù)都在 request.body 里,取出來自行處理
六 Django內(nèi)置的serializers(把對象序列化成json字符串)
?
from django.core import serializers?
from django.core import serializers def test(request):book_list = Book.objects.all() ret = serializers.serialize("json", book_list)return HttpResponse(ret)?
?
七:Ajax登錄驗證
View層
from django.shortcuts import render from app01 import models from django.http import JsonResponse # Create your views here.def index(request):if request.method=='GET':return render(request,'index.html')def login(request):if request.method=='GET':return render(request,'index.html')else:name=request.POST.get('name')password=request.POST.get('password')dic={'status':100,'msg':None}user=models.User.objects.all().filter(name=name,password=password).first()if user:dic['msg']='login successfully'else:dic['status']=101dic['msg']='用戶名或密碼錯誤'return JsonResponse(dic)?
index.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><script src="/static/jquery-3.3.1.js"></script><title>Title</title> </head> <body> <p>用戶名:<input type="text" name="name" id="name"></p> <p>密碼:<input type="text" name="password" id="password"></p> <p><button id="btn">提交</button> </p> <span id="error"></span> <script>$('#btn').click(function () {$.ajax({url: '/login/',type: 'post',data: {'name': $("#name").val(), 'pwd': $("#password").val()},dataType: 'json',success: function (data) {if (data.status == 100) {location.href = 'https://www.baidu.com'} else {$("#error").html(data.msg).css({'color': 'red'})setTimeout(function () {$("#error").html("")//alert(1) }, 1000)}}})}) </script> </body> </html>?
models層
from django.db import models # Create your models here. class User(models.Model):name=models.CharField(max_length=32)password=models.CharField(max_length=32)?
轉(zhuǎn)載于:https://www.cnblogs.com/ouyang99-/p/9986483.html
總結(jié)
以上是生活随笔為你收集整理的Django和Ajax的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gram创建邮箱
- 下一篇: Python-流程控制之循环