當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
AJAX初识(原生JS版AJAX和Jquery版AJAX)
生活随笔
收集整理的這篇文章主要介紹了
AJAX初识(原生JS版AJAX和Jquery版AJAX)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、什么是JSON
1.介紹JSON獨(dú)立于語(yǔ)言,是一種與語(yǔ)言無(wú)關(guān)的數(shù)據(jù)格式。JSON指的是JavaScript對(duì)象表示法(JavaScript Object Notation)JSON是輕量級(jí)的文本數(shù)據(jù)交換格式JSON具有自我描述性,更易理解JSON使用JavaScript語(yǔ)法來(lái)描述數(shù)據(jù)對(duì)象,但是JSON仍然獨(dú)立于語(yǔ)言和平臺(tái)。JSON解析器和JSON庫(kù)支持許多不同的編程語(yǔ)言。2. Python中JSON操作import json1. json.dumps() --> 序列化 /json.dump() --> 文件操作 2. json.loads() --> 反序列化 /json.load() --> 文件操作3. JS中JSON操作1. JSON.stringify() --> 序列化2. JSON.parse() --> 反序列化
4. 例如合格的json對(duì)象["one", "two", "three"]{ "one": 1, "two": 2, "three": 3 }{"names": ["張三", "李四"] }[ { "name": "張三"}, {"name": "李四"} ]
不合格的json對(duì)象{ name: "張三", 'age': 32 } // 屬性名必須使用雙引號(hào)[32, 64, 128, 0xFFF] // 不能使用十六進(jìn)制值{ "name": "張三", "age": undefined } // 不能使用undefined{ "name": "張三","birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),"getName": function() {return this.name;} // 不能使用函數(shù)和日期對(duì)象}5. 與XML的比較JSON 格式于2001年由 Douglas Crockford 提出,目的就是取代繁瑣笨重的 XML 格式。JSON 格式有兩個(gè)顯著的優(yōu)點(diǎn):書(shū)寫(xiě)簡(jiǎn)單,一目了然;符合 JavaScript 原生語(yǔ)法,可以由解釋引擎直接處理,不用另外添加解析代碼。所以,JSON迅速被接受,已經(jīng)成為各大網(wǎng)站交換數(shù)據(jù)的標(biāo)準(zhǔn)格式,并被寫(xiě)入ECMAScript 5,成為標(biāo)準(zhǔn)的一部分。XML和JSON都使用結(jié)構(gòu)化方法來(lái)標(biāo)記數(shù)據(jù),下面來(lái)做一個(gè)簡(jiǎn)單的比較。用XML表示中國(guó)部分省市數(shù)據(jù)如下: <?xml version="1.0" encoding="utf-8"?><country><name>中國(guó)</name><province><name>黑龍江</name><cities><city>哈爾濱</city><city>大慶</city></cities></province><province><name>廣東</name><cities><city>廣州</city><city>深圳</city><city>珠海</city></cities></province><province><name>臺(tái)灣</name><cities><city>臺(tái)北</city><city>高雄</city></cities></province><province><name>新疆</name><cities><city>烏魯木齊</city></cities></province></country> View Code
用JSON表示如下: {"name": "中國(guó)","province": [{"name": "黑龍江","cities": {"city": ["哈爾濱", "大慶"]}}, {"name": "廣東","cities": {"city": ["廣州", "深圳", "珠海"]}}, {"name": "臺(tái)灣","cities": {"city": ["臺(tái)北", "高雄"]}}, {"name": "新疆","cities": {"city": ["烏魯木齊"]}}]} View Code 由上面的兩端代碼可以看出,JSON 簡(jiǎn)單的語(yǔ)法格式和清晰的層次結(jié)構(gòu)明顯要比 XML 容易閱讀,并且在數(shù)據(jù)交換方面,由于 JSON 所使用的字符要比 XML 少得多,可以大大得節(jié)約傳輸數(shù)據(jù)所占用得帶寬二、AJAX簡(jiǎn)介 1、介紹AJAX(Asynchronous Javascript And XML)翻譯成中文就是“異步的Javascript和XML”。即使用Javascript語(yǔ)言與服務(wù)器進(jìn)行異步交互,傳輸?shù)臄?shù)據(jù)為XML(當(dāng)然,傳輸?shù)臄?shù)據(jù)不只是XML)。AJAX 不是新的編程語(yǔ)言,而是一種使用現(xiàn)有標(biāo)準(zhǔn)的新方法。AJAX 最大的優(yōu)點(diǎn)是在不重新加載整個(gè)頁(yè)面的情況下,可以與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁(yè)內(nèi)容。(這一特點(diǎn)給用戶的感受是在不知不覺(jué)中完成請(qǐng)求和響應(yīng)過(guò)程)AJAX 不需要任何瀏覽器插件,但需要用戶允許JavaScript在瀏覽器上執(zhí)行。同步交互:客戶端發(fā)出一個(gè)請(qǐng)求后,需要等待服務(wù)器響應(yīng)結(jié)束后,才能發(fā)出第二個(gè)請(qǐng)求;異步交互:客戶端發(fā)出一個(gè)請(qǐng)求后,無(wú)需等待服務(wù)器響應(yīng)結(jié)束,就可以發(fā)出第二個(gè)請(qǐng)求。2、AJAX常見(jiàn)應(yīng)用情景 1.搜索引擎根據(jù)用戶輸入的關(guān)鍵字,自動(dòng)提示檢索關(guān)鍵字。2.還有一個(gè)很重要的應(yīng)用場(chǎng)景就是注冊(cè)時(shí)候的用戶名的查重。其實(shí)這里就使用了AJAX技術(shù)!當(dāng)文件框發(fā)生了輸入變化時(shí),使用AJAX技術(shù)向服務(wù)器發(fā)送一個(gè)請(qǐng)求,然后服務(wù)器會(huì)把查詢(xún)到的結(jié)果響應(yīng)給瀏覽器,最后再把后端返回的結(jié)果展示出來(lái)。當(dāng)輸入用戶名后,把光標(biāo)移動(dòng)到其他表單項(xiàng)上時(shí),瀏覽器會(huì)使用AJAX技術(shù)向服務(wù)器發(fā)出請(qǐng)求,服務(wù)器會(huì)查詢(xún)你輸入的用戶名是否存在,最終服務(wù)器返回true表示名你輸入的用戶名已經(jīng)存在了,瀏覽器在得到結(jié)果后顯示“用戶名已被注冊(cè)!”。整個(gè)過(guò)程中頁(yè)面沒(méi)有刷新,只是局部刷新了;在請(qǐng)求發(fā)出后,瀏覽器不用等待服務(wù)器響應(yīng)結(jié)果就可以進(jìn)行其他操作;3、AJAX的優(yōu)缺點(diǎn)優(yōu)點(diǎn):AJAX使用JavaScript技術(shù)向服務(wù)器發(fā)送異步請(qǐng)求;AJAX請(qǐng)求無(wú)須刷新整個(gè)頁(yè)面;因?yàn)榉?wù)器響應(yīng)內(nèi)容不再是整個(gè)頁(yè)面,而是頁(yè)面中的部分內(nèi)容,所以AJAX性能高;
缺點(diǎn):
AJAX濫用對(duì)服務(wù)端壓力比較大三、JS實(shí)現(xiàn)AJAX 1.注意:一般我們都不使用原生的JS實(shí)現(xiàn)AJAX,因?yàn)樵鶭S的步驟太繁瑣(下面會(huì)介紹簡(jiǎn)單的AJAX實(shí)現(xiàn))2. JS實(shí)現(xiàn)AJAX模板 var b2 = document.getElementById("b2");b2.onclick = function () {// 原生JSvar xmlHttp = new XMLHttpRequest();xmlHttp.open("POST", "/ajax_test/", true);xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlHttp.send("username=q1mi&password=123456");xmlHttp.onreadystatechange = function () {if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {alert(xmlHttp.responseText);}};}; View Code
2、方式2 通過(guò)獲取返回的cookie中的字符串 放置在請(qǐng)求頭中發(fā)送(需要引入一個(gè)jquery.cookie.js插件) $.ajax({url: "/login/",type: "POST",headers: {"X-CSRFToken": $.cookie('csrftoken')}, // 從Cookie取csrftoken,并設(shè)置到請(qǐng)求頭中data: {"username": "xm", "password": 123},success: function (res) {console.log(res);} }) View Code
3、方式3 自己寫(xiě)一個(gè)getCookie方法 創(chuàng)建一個(gè)JS文件,代碼如下: (這是官網(wǎng)提供的代碼) // 定義一個(gè)從本地獲取Cookie的函數(shù) function getCookie(name) {var cookieValue = null;if (document.cookie && document.cookie !== '') {var cookies = document.cookie.split(';');for (var i = 0; i < cookies.length; i++) {var cookie = jQuery.trim(cookies[i]);// Does this cookie string begin with the name we want?if (cookie.substring(0, name.length + 1) === (name + '=')) {cookieValue = decodeURIComponent(cookie.substring(name.length + 1));break;}}}return cookieValue; } // 調(diào)用上面定義的函數(shù),從本地取出csrftoken對(duì)應(yīng)的Cookie值 var csrftoken = getCookie('csrftoken');function csrfSafeMethod(method) {// these HTTP methods do not require CSRF protectionreturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }$.ajaxSetup({beforeSend: function (xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {// 給所有的AJAX請(qǐng)求設(shè)置請(qǐng)求頭:xhr.setRequestHeader("X-CSRFToken", csrftoken);}} }); View Code 使用的時(shí)候只需要導(dǎo)入你這個(gè)JS代碼,ajxa請(qǐng)求就不需要自己手動(dòng)添加csrf的值了注意:方式3和方式2其實(shí)是同一種方法,只是方式2是使用別人寫(xiě)好的插件,方式3是自己寫(xiě)而已。如果使用從cookie中取csrftoken的方式,需要確保cookie存在csrftoken值。如果你的視圖渲染的HTML文件中沒(méi)有包含 {% csrf_token %},Django可能不會(huì)設(shè)置CSRFtoken的cookie。這個(gè)時(shí)候需要使用ensure_csrf_cookie()裝飾器強(qiáng)制設(shè)置Cookie。使用方式2和3需要在views.py的視圖函數(shù)中加上這個(gè)裝飾器確保瀏覽器中有cookie django.views.decorators.csrf import ensure_csrf_cookie@ensure_csrf_cookie def login(request):pass五、jQuery實(shí)現(xiàn)的AJAX 1、最基本的ajax 發(fā)送ajax請(qǐng)求 $.ajax({})參數(shù):url: 提交到哪個(gè)URL地址type: 提交的方式data: {你要發(fā)送的數(shù)據(jù)}success: function (res) {請(qǐng)求發(fā)送過(guò)去,被正常響應(yīng)后執(zhí)行的函數(shù),res是后端返回來(lái)的數(shù)據(jù)}error: function (err) {請(qǐng)求發(fā)送過(guò)去,響應(yīng)失敗時(shí)執(zhí)行的函數(shù)}2、驗(yàn)證用戶名是否存在的例子 1. models.py class UserInfo(models.Model):username = models.CharField(max_length=12)password = models.CharField(max_length=20)2. HTML代碼 <!DOCTYPE html> <html lang="zh-CN"> <head><meta http-equiv="content-type" charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Login</title> </head><body><p><label for="i1">用戶名:</label><input type="text" name="username" id="i1"><span id="s1" style="color: red;"></span> </p>{% csrf_token %}<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript">$("#i1").blur(function () {//輸入框失去焦點(diǎn)時(shí)觸發(fā)ajax請(qǐng)求 $.ajax({url: '/regirest/',type: 'POST',data: {username: $("#i1").val(), // 防止跨站偽造請(qǐng)求,需要添加csrf_token的值 csrfmiddlewaretoken: $("[name = 'csrfmiddlewaretoken']").val(),},success: function (res) {$("#s1").text(res)}})}) </script></body> </html> View Code
3. views.py def regirest(request):if request.method == 'POST':username = request.POST.get('username')is_exist = UserInfo.objects.filter(username=username)if is_exist:return HttpResponse('用戶名已存在')else:return HttpResponse('用戶名可用')return render(request, 'regirest.html') View Code
3、用戶登錄例子 1. HTML代碼 <!DOCTYPE html> <html lang="zh-CN"> <head><meta http-equiv="content-type" charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Login</title> </head><body><div><h1>歡迎登錄</h1></div> <div><p><label for="i1">用戶名:</label><input type="text" id="i1"></p><p><label for="i2">密碼:</label><input type="password" id="i2"></p><p><button type="button" id="b1">登錄</button><span style="color: red"></span></p>{% csrf_token %} </div><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript">$("#b1").click(function () {$.ajax({url: '/login/',type: 'POST',data: {username: $("#i1").val(),pwd: $("#i2").val(),// 防止跨站偽造請(qǐng)求,需要添加csrf_token的值 csrfmiddlewaretoken: $("[name = 'csrfmiddlewaretoken']").val(),},success: function (res) {if (res.code === 0){location.href = res.next_url}else {// 有錯(cuò)誤 $("#b1+span").text(res.err_msg)}}})}) </script></body> </html> View Code
2. views.py class LoginView(views.View):def get(self, request):return render(request, 'login.html')def post(self, request):username = request.POST.get('username')pwd = request.POST.get('pwd')is_ok = UserInfo.objects.filter(username=username, password=pwd)res = {'code': 0} # 登錄狀態(tài) 0代表登錄成功if is_ok:# 登錄成功,跳轉(zhuǎn)到regirest頁(yè)面res['next_url'] = '/regirest/'return JsonResponse(res)else:# 登錄失敗,在頁(yè)面上顯示錯(cuò)誤提示res['code'] = 1res['err_msg'] = '用戶名或者密碼錯(cuò)誤'return JsonResponse(res) View Code
2.views.py class UploadView(views.View):def get(self, request):return render(request, 'upload.html')def post(self, request):file_obj = request.FILES.get('xx')file_name = file_obj.namewith open(file_name, 'wb') as f:for c in file_obj.chunks():f.write(c)return HttpResponse('上傳成功!') View Code
4. 例如合格的json對(duì)象["one", "two", "three"]{ "one": 1, "two": 2, "three": 3 }{"names": ["張三", "李四"] }[ { "name": "張三"}, {"name": "李四"} ]
不合格的json對(duì)象{ name: "張三", 'age': 32 } // 屬性名必須使用雙引號(hào)[32, 64, 128, 0xFFF] // 不能使用十六進(jìn)制值{ "name": "張三", "age": undefined } // 不能使用undefined{ "name": "張三","birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),"getName": function() {return this.name;} // 不能使用函數(shù)和日期對(duì)象}5. 與XML的比較JSON 格式于2001年由 Douglas Crockford 提出,目的就是取代繁瑣笨重的 XML 格式。JSON 格式有兩個(gè)顯著的優(yōu)點(diǎn):書(shū)寫(xiě)簡(jiǎn)單,一目了然;符合 JavaScript 原生語(yǔ)法,可以由解釋引擎直接處理,不用另外添加解析代碼。所以,JSON迅速被接受,已經(jīng)成為各大網(wǎng)站交換數(shù)據(jù)的標(biāo)準(zhǔn)格式,并被寫(xiě)入ECMAScript 5,成為標(biāo)準(zhǔn)的一部分。XML和JSON都使用結(jié)構(gòu)化方法來(lái)標(biāo)記數(shù)據(jù),下面來(lái)做一個(gè)簡(jiǎn)單的比較。用XML表示中國(guó)部分省市數(shù)據(jù)如下: <?xml version="1.0" encoding="utf-8"?><country><name>中國(guó)</name><province><name>黑龍江</name><cities><city>哈爾濱</city><city>大慶</city></cities></province><province><name>廣東</name><cities><city>廣州</city><city>深圳</city><city>珠海</city></cities></province><province><name>臺(tái)灣</name><cities><city>臺(tái)北</city><city>高雄</city></cities></province><province><name>新疆</name><cities><city>烏魯木齊</city></cities></province></country> View Code
用JSON表示如下: {"name": "中國(guó)","province": [{"name": "黑龍江","cities": {"city": ["哈爾濱", "大慶"]}}, {"name": "廣東","cities": {"city": ["廣州", "深圳", "珠海"]}}, {"name": "臺(tái)灣","cities": {"city": ["臺(tái)北", "高雄"]}}, {"name": "新疆","cities": {"city": ["烏魯木齊"]}}]} View Code 由上面的兩端代碼可以看出,JSON 簡(jiǎn)單的語(yǔ)法格式和清晰的層次結(jié)構(gòu)明顯要比 XML 容易閱讀,并且在數(shù)據(jù)交換方面,由于 JSON 所使用的字符要比 XML 少得多,可以大大得節(jié)約傳輸數(shù)據(jù)所占用得帶寬二、AJAX簡(jiǎn)介 1、介紹AJAX(Asynchronous Javascript And XML)翻譯成中文就是“異步的Javascript和XML”。即使用Javascript語(yǔ)言與服務(wù)器進(jìn)行異步交互,傳輸?shù)臄?shù)據(jù)為XML(當(dāng)然,傳輸?shù)臄?shù)據(jù)不只是XML)。AJAX 不是新的編程語(yǔ)言,而是一種使用現(xiàn)有標(biāo)準(zhǔn)的新方法。AJAX 最大的優(yōu)點(diǎn)是在不重新加載整個(gè)頁(yè)面的情況下,可以與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁(yè)內(nèi)容。(這一特點(diǎn)給用戶的感受是在不知不覺(jué)中完成請(qǐng)求和響應(yīng)過(guò)程)AJAX 不需要任何瀏覽器插件,但需要用戶允許JavaScript在瀏覽器上執(zhí)行。同步交互:客戶端發(fā)出一個(gè)請(qǐng)求后,需要等待服務(wù)器響應(yīng)結(jié)束后,才能發(fā)出第二個(gè)請(qǐng)求;異步交互:客戶端發(fā)出一個(gè)請(qǐng)求后,無(wú)需等待服務(wù)器響應(yīng)結(jié)束,就可以發(fā)出第二個(gè)請(qǐng)求。2、AJAX常見(jiàn)應(yīng)用情景 1.搜索引擎根據(jù)用戶輸入的關(guān)鍵字,自動(dòng)提示檢索關(guān)鍵字。2.還有一個(gè)很重要的應(yīng)用場(chǎng)景就是注冊(cè)時(shí)候的用戶名的查重。其實(shí)這里就使用了AJAX技術(shù)!當(dāng)文件框發(fā)生了輸入變化時(shí),使用AJAX技術(shù)向服務(wù)器發(fā)送一個(gè)請(qǐng)求,然后服務(wù)器會(huì)把查詢(xún)到的結(jié)果響應(yīng)給瀏覽器,最后再把后端返回的結(jié)果展示出來(lái)。當(dāng)輸入用戶名后,把光標(biāo)移動(dòng)到其他表單項(xiàng)上時(shí),瀏覽器會(huì)使用AJAX技術(shù)向服務(wù)器發(fā)出請(qǐng)求,服務(wù)器會(huì)查詢(xún)你輸入的用戶名是否存在,最終服務(wù)器返回true表示名你輸入的用戶名已經(jīng)存在了,瀏覽器在得到結(jié)果后顯示“用戶名已被注冊(cè)!”。整個(gè)過(guò)程中頁(yè)面沒(méi)有刷新,只是局部刷新了;在請(qǐng)求發(fā)出后,瀏覽器不用等待服務(wù)器響應(yīng)結(jié)果就可以進(jìn)行其他操作;3、AJAX的優(yōu)缺點(diǎn)優(yōu)點(diǎn):AJAX使用JavaScript技術(shù)向服務(wù)器發(fā)送異步請(qǐng)求;AJAX請(qǐng)求無(wú)須刷新整個(gè)頁(yè)面;因?yàn)榉?wù)器響應(yīng)內(nèi)容不再是整個(gè)頁(yè)面,而是頁(yè)面中的部分內(nèi)容,所以AJAX性能高;
缺點(diǎn):
AJAX濫用對(duì)服務(wù)端壓力比較大三、JS實(shí)現(xiàn)AJAX 1.注意:一般我們都不使用原生的JS實(shí)現(xiàn)AJAX,因?yàn)樵鶭S的步驟太繁瑣(下面會(huì)介紹簡(jiǎn)單的AJAX實(shí)現(xiàn))2. JS實(shí)現(xiàn)AJAX模板 var b2 = document.getElementById("b2");b2.onclick = function () {// 原生JSvar xmlHttp = new XMLHttpRequest();xmlHttp.open("POST", "/ajax_test/", true);xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlHttp.send("username=q1mi&password=123456");xmlHttp.onreadystatechange = function () {if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {alert(xmlHttp.responseText);}};}; View Code
?
四、AJAX請(qǐng)求設(shè)置csrf_token 1、方式1 通過(guò)獲取隱藏的input標(biāo)簽中的csrfmiddlewaretoken值,放置在data中發(fā)送。 $.ajax({url: "/login/",type: "POST",data: {"username": "xm","password": 123,"csrfmiddlewaretoken": $("[name = 'csrfmiddlewaretoken']").val() // 使用jQuery取出csrfmiddlewaretoken的值,拼接到data中 },success: function (res) {console.log(res);} }) View Code2、方式2 通過(guò)獲取返回的cookie中的字符串 放置在請(qǐng)求頭中發(fā)送(需要引入一個(gè)jquery.cookie.js插件) $.ajax({url: "/login/",type: "POST",headers: {"X-CSRFToken": $.cookie('csrftoken')}, // 從Cookie取csrftoken,并設(shè)置到請(qǐng)求頭中data: {"username": "xm", "password": 123},success: function (res) {console.log(res);} }) View Code
3、方式3 自己寫(xiě)一個(gè)getCookie方法 創(chuàng)建一個(gè)JS文件,代碼如下: (這是官網(wǎng)提供的代碼) // 定義一個(gè)從本地獲取Cookie的函數(shù) function getCookie(name) {var cookieValue = null;if (document.cookie && document.cookie !== '') {var cookies = document.cookie.split(';');for (var i = 0; i < cookies.length; i++) {var cookie = jQuery.trim(cookies[i]);// Does this cookie string begin with the name we want?if (cookie.substring(0, name.length + 1) === (name + '=')) {cookieValue = decodeURIComponent(cookie.substring(name.length + 1));break;}}}return cookieValue; } // 調(diào)用上面定義的函數(shù),從本地取出csrftoken對(duì)應(yīng)的Cookie值 var csrftoken = getCookie('csrftoken');function csrfSafeMethod(method) {// these HTTP methods do not require CSRF protectionreturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }$.ajaxSetup({beforeSend: function (xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {// 給所有的AJAX請(qǐng)求設(shè)置請(qǐng)求頭:xhr.setRequestHeader("X-CSRFToken", csrftoken);}} }); View Code 使用的時(shí)候只需要導(dǎo)入你這個(gè)JS代碼,ajxa請(qǐng)求就不需要自己手動(dòng)添加csrf的值了注意:方式3和方式2其實(shí)是同一種方法,只是方式2是使用別人寫(xiě)好的插件,方式3是自己寫(xiě)而已。如果使用從cookie中取csrftoken的方式,需要確保cookie存在csrftoken值。如果你的視圖渲染的HTML文件中沒(méi)有包含 {% csrf_token %},Django可能不會(huì)設(shè)置CSRFtoken的cookie。這個(gè)時(shí)候需要使用ensure_csrf_cookie()裝飾器強(qiáng)制設(shè)置Cookie。使用方式2和3需要在views.py的視圖函數(shù)中加上這個(gè)裝飾器確保瀏覽器中有cookie django.views.decorators.csrf import ensure_csrf_cookie@ensure_csrf_cookie def login(request):pass五、jQuery實(shí)現(xiàn)的AJAX 1、最基本的ajax 發(fā)送ajax請(qǐng)求 $.ajax({})參數(shù):url: 提交到哪個(gè)URL地址type: 提交的方式data: {你要發(fā)送的數(shù)據(jù)}success: function (res) {請(qǐng)求發(fā)送過(guò)去,被正常響應(yīng)后執(zhí)行的函數(shù),res是后端返回來(lái)的數(shù)據(jù)}error: function (err) {請(qǐng)求發(fā)送過(guò)去,響應(yīng)失敗時(shí)執(zhí)行的函數(shù)}2、驗(yàn)證用戶名是否存在的例子 1. models.py class UserInfo(models.Model):username = models.CharField(max_length=12)password = models.CharField(max_length=20)2. HTML代碼 <!DOCTYPE html> <html lang="zh-CN"> <head><meta http-equiv="content-type" charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Login</title> </head><body><p><label for="i1">用戶名:</label><input type="text" name="username" id="i1"><span id="s1" style="color: red;"></span> </p>{% csrf_token %}<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript">$("#i1").blur(function () {//輸入框失去焦點(diǎn)時(shí)觸發(fā)ajax請(qǐng)求 $.ajax({url: '/regirest/',type: 'POST',data: {username: $("#i1").val(), // 防止跨站偽造請(qǐng)求,需要添加csrf_token的值 csrfmiddlewaretoken: $("[name = 'csrfmiddlewaretoken']").val(),},success: function (res) {$("#s1").text(res)}})}) </script></body> </html> View Code
3. views.py def regirest(request):if request.method == 'POST':username = request.POST.get('username')is_exist = UserInfo.objects.filter(username=username)if is_exist:return HttpResponse('用戶名已存在')else:return HttpResponse('用戶名可用')return render(request, 'regirest.html') View Code
3、用戶登錄例子 1. HTML代碼 <!DOCTYPE html> <html lang="zh-CN"> <head><meta http-equiv="content-type" charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Login</title> </head><body><div><h1>歡迎登錄</h1></div> <div><p><label for="i1">用戶名:</label><input type="text" id="i1"></p><p><label for="i2">密碼:</label><input type="password" id="i2"></p><p><button type="button" id="b1">登錄</button><span style="color: red"></span></p>{% csrf_token %} </div><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript">$("#b1").click(function () {$.ajax({url: '/login/',type: 'POST',data: {username: $("#i1").val(),pwd: $("#i2").val(),// 防止跨站偽造請(qǐng)求,需要添加csrf_token的值 csrfmiddlewaretoken: $("[name = 'csrfmiddlewaretoken']").val(),},success: function (res) {if (res.code === 0){location.href = res.next_url}else {// 有錯(cuò)誤 $("#b1+span").text(res.err_msg)}}})}) </script></body> </html> View Code
2. views.py class LoginView(views.View):def get(self, request):return render(request, 'login.html')def post(self, request):username = request.POST.get('username')pwd = request.POST.get('pwd')is_ok = UserInfo.objects.filter(username=username, password=pwd)res = {'code': 0} # 登錄狀態(tài) 0代表登錄成功if is_ok:# 登錄成功,跳轉(zhuǎn)到regirest頁(yè)面res['next_url'] = '/regirest/'return JsonResponse(res)else:# 登錄失敗,在頁(yè)面上顯示錯(cuò)誤提示res['code'] = 1res['err_msg'] = '用戶名或者密碼錯(cuò)誤'return JsonResponse(res) View Code
?
4、上傳文件例子 1. HTML代碼 <!DOCTYPE html> <html lang="en"> <head><meta http-equiv="content-type" charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Upload</title> </head> <body>{% csrf_token %}<h1>上傳文件</h1> <div> <input type="file" id="f1"> <button id="b1"> 上傳</button> </div> <span style="color: red" id="s1"></span><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script>$('#b1').click(function () {// 取到要上傳的文件數(shù)據(jù),存到一個(gè)對(duì)象中var fdObj = new FormData();fdObj.append('xx', $('#f1')[0].files[0]);// 在請(qǐng)求的數(shù)據(jù)中添加csrftokrnvar csrfToken = $('[name="csrfmiddlewaretoken"]').val();fdObj.append('csrfmiddlewaretoken', csrfToken);// 發(fā)ajax請(qǐng)求 $.ajax({url: '/upload/',type: 'post',data: fdObj,processData: false, // 告訴jQuery不要處理我上傳的數(shù)據(jù) contentType: false, // 告訴jQuery不要設(shè)置請(qǐng)求的文件類(lèi)型,這兩個(gè)參數(shù)相當(dāng)于enctype="multipart/form-data" success: function (res) {$("#s1").text(res);}})}) </script> </body> </html> View Code2.views.py class UploadView(views.View):def get(self, request):return render(request, 'upload.html')def post(self, request):file_obj = request.FILES.get('xx')file_name = file_obj.namewith open(file_name, 'wb') as f:for c in file_obj.chunks():f.write(c)return HttpResponse('上傳成功!') View Code
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/yidashi110/p/10091961.html
總結(jié)
以上是生活随笔為你收集整理的AJAX初识(原生JS版AJAX和Jquery版AJAX)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 为什么dubbo的调用重试不建议设置成超
- 下一篇: JavaScript——根据数组中的某个