日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Django和Ajax

發布時間:2024/4/17 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django和Ajax 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文目錄

  • 一 什么是Ajax
  • 二 基于jquery的Ajax實現
  • 三 案例
  • 四 文件上傳
  • 五 Ajax提交json格式數據
  • 六 Django內置的serializers(把對象序列化成json字符串)
  • 七:Ajax登錄驗證

?

一 什么是Ajax

?

AJAXAsynchronous Javascript And XML)翻譯成中文就是異步JavascriptXML”。即使用Javascript語言與服務器進行異步交互,傳輸的數據為XML(當然,傳輸的數據不只是XML,現在更多使用json數據)。

?

  • 同步交互:客戶端發出一個請求后,需要等待服務器響應結束后,才能發出第二個請求;
  • 異步交互:客戶端發出一個請求后,無需等待服務器響應結束,就可以發出第二個請求。

?

AJAX除了異步的特點外,還有一個就是:瀏覽器頁面局部刷新;(這一特點給用戶的感受是在不知不覺中完成請求和響應過程)

?

場景:

優點:

  • AJAX使用Javascript技術向服務器發送異步請求
  • AJAX無須刷新整個頁面

二 基于jquery的Ajax實現

<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---->服務器------>Ajax執行流程圖

三 案例

一 通過Ajax,實現前端輸入兩個數字,服務器做加法,返回到前端頁面

def test_ajax(requests):n1=int(request.POST.get('n1'))n2=int(request.POST.get('n2'))return HttpResponse(n1+n2) 視圖函數 $("#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提交給服務器,服務器驗證后返回響應信息,客戶端通過響應信息確定是否登錄成功,成功,則跳轉到首頁,否則,在頁面上顯示相應的錯誤信息

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)) 視圖函數 $("#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

這應該是最常見的 POST 提交數據的方式了。瀏覽器的原生 <form> 表單,如果不設置?enctype?屬性,那么最終就會以 application/x-www-form-urlencoded 方式提交數據。請求類似于下面這樣(無關的請求頭在本文中都省略掉了):

POST http://www.example.com HTTP/1.1 Content-Type: application/x-www-form-urlencoded;charset=utf-8user=lqz&age=22

2 multipart/form-data

這又是一個常見的 POST 數據提交的方式。我們使用表單上傳文件時,必須讓 <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--

這個例子稍微復雜點。首先生成了一個 boundary 用于分割不同的字段,為了避免與正文內容重復,boundary 很長很復雜。然后 Content-Type 里指明了數據是以 multipart/form-data 來編碼,本次請求的 boundary 是什么內容。消息主體里按照字段個數又分為多個結構類似的部分,每部分都是以?--boundary?開始,緊接著是內容描述信息,然后是回車,最后是字段具體內容(文本或二進制)。如果傳輸的是文件,還要包含文件名和文件類型信息。消息主體最后以?--boundary--?標示結束。關于 multipart/form-data 的詳細定義,請前往?rfc1867?查看。

這種方式一般用來上傳文件,各大服務端語言對它也有著良好的支持。

上面提到的這兩種 POST 數據的方式,都是瀏覽器原生支持的,而且現階段標準中原生 <form> 表單也只支持這兩種方式(通過 <form> 元素的?enctype?屬性指定,默認為?application/x-www-form-urlencoded。其實?enctype?還支持?text/plain,不過用得非常少)。

隨著越來越多的 Web 站點,尤其是 WebApp,全部使用 Ajax 進行數據交互之后,我們完全可以定義新的數據提交方式,給開發帶來更多便利。

3 application/json

application/json 這個 Content-Type 作為響應頭大家肯定不陌生。實際上,現在越來越多的人把它作為請求頭,用來告訴服務端消息主體是序列化后的 JSON 字符串。由于 JSON 規范的流行,除了低版本 IE 之外的各大瀏覽器都原生支持 JSON.stringify,服務端語言也都有處理 JSON 的函數,使用 JSON 不會遇上什么麻煩。

JSON 格式支持比鍵值對復雜得多的結構化數據,這一點也很有用。記得我幾年前做一個項目時,需要提交的數據層次非常深,我就是把數據 JSON 序列化之后來提交的。不過當時我是把 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"

視圖函數:

def file_put(request):if request.method=='GET':return render(request,'file_put.html')else:# print(request.POST)# print(request.POST)print(request.body) # 原始的請求體數據 print(request.GET) # GET請求數據 print(request.POST) # POST請求數據 print(request.FILES) # 上傳的文件數據# 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不要去處理發送的數據contentType:false,// 告訴jQuery不要去設置Content-Type請求頭data:formdata,success:function (data) {console.log(data)}})})

瀏覽器請求頭為:

Content-Type:

?

multipart/form-data; boundary=----WebKitFormBoundaryA5O53SvUXJaF11O2

五 Ajax提交json格式數據

$("#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), //轉換成json字符串格式success:function (data) {console.log(data)}})})

提交到服務器的數據都在 request.body 里,取出來自行處理

六 Django內置的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)

?

轉載于:https://www.cnblogs.com/ouyang99-/p/9986483.html

總結

以上是生活随笔為你收集整理的Django和Ajax的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。