AJAX(Asynchronous Javascript And XML)優勢是在不從新加載整個頁面的狀況下,能夠與服務器交換數據並更新部分網頁內容javascript
優勢:html
1.ajax使用JavaScript技術向服務器發送異步請求前端
2.ajax請求無需刷新整個頁面(瀏覽器局部刷新)java
3.服務器響應內容再也不是整個頁面,而是頁面中的部份內容,因此ajax性能高python
基本格式jquery
//基於按鈕點擊事件實現的 <script src="{% static 'js/jquery.js' %}"></script> <script> $('#sub').click(function () { //$.ajax({鍵值對參數}) $.ajax({ url:"{% url 'login' %}", type:'post', data:{'username':uname,'pwd':pwd,'csrfmiddlewaretoken':csrf_token}, success:function (response) { // response這個參數名字是自定義的 } }) }) </script>
1.jQuery的實現ajax
<button class="send_Ajax">send_Ajax</button> <script> $(".send_Ajax").click(function(){ $.ajax({ url:"/handle_Ajax/", type:"POST", data:{username:"tom",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>
2.原生Js實現django
var bt2 = document.getElementById("bt2"); bt2.onclick = function () { // 原生JS var xmlHttp = new XMLHttpRequest(); xmlHttp.open("POST", "/ajax_test/", true); xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlHttp.send("username=tom&password=123"); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4 && xmlHttp.status === 200) { alert(xmlHttp.responseText); } }; };
用一個簡單的登陸驗證明例來講明,用戶名和密碼正確提示成功.不然顯示失敗json
發送的數據若是是字典時,其中的引號必須是雙引號,不然傳到前端使用會報錯,瀏覽器
如{ 「data」: data } , 不要用{‘data’: data}
這樣發送的數據,前端就不用解析了,能夠直接看成對象來使用
views.py
from django.shortcuts import render,redirect,HttpResponse from django.http import JsonResponse from app01 import models # Create your views here. def login(request): if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") print(username, password) ret = models.Userinfo.objects.filter(username=username,password=password) print(ret) a = {"status":None} if ret: a["status"] = True print(a) return JsonResponse(a) else: return HttpResponse("fail") else: return render(request,"login.html")
login.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% csrf_token %} 用戶名: <input type="text" id="username"> 密碼: <input type="password" id="password"> <button id="sub">登錄</button> <span id="mag" style="color: red;font-size: 12px;"></span> <script src="{% static 'js/jquery.min.js' %}"></script> <script> $("#sub").click(function () { var uname = $("#username").val(); var pwd = $("#password").val(); var csrf_token = $("input[name=csrfmiddlewaretoken]").val(); $.ajax({ url:"{% url 'login' %}", type:"post", data:{"username":uname,"password":pwd,"csrfmiddlewaretoken":csrf_token}, success:function (response) { console.log(response, typeof response); if (response.status){ $("span").text("登錄成功"); }else{ $("span").text("失敗"); } } } ) }) </script> </body> </html>
HttpResponse加一個頭就能夠了,這樣使用HttpResponse(data, content_type=content_type='application/json')
這樣在前端html頁面就不用解析json格式了,能夠直接做爲對象調用數據
views.py
from django.shortcuts import render,redirect,HttpResponse from django.http import JsonResponse from app01 import models import json # Create your views here. def login(request): if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") print(username, password) ret = models.Userinfo.objects.filter(username=username,password=password) print(ret) a = {"status":None} if ret: a["status"] = True print(a) msg = json.dumps(a) return HttpResponse(msg, content_type='application/json') else: msg = json.dumps(a) return HttpResponse(msg, content_type='application/json') else: return render(request,"login.html")
login.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% csrf_token %} 用戶名: <input type="text" id="username"> 密碼: <input type="password" id="password"> <button id="sub">登錄</button> <span id="mag" style="color: red;font-size: 12px;"></span> <script src="{% static 'js/jquery.min.js' %}"></script> # 經過別名引入靜態文件 <script> $("#sub").click(function () { var uname = $("#username").val(); var pwd = $("#password").val(); var csrf_token = $("input[name=csrfmiddlewaretoken]").val(); $.ajax({ url:"{% url 'login' %}", type:"post", data:{"username":uname,"password":pwd,"csrfmiddlewaretoken":csrf_token}, success:function (response) { console.log(response, typeof response); if (response.status){ $("span").text("登錄成功"); }else{ $("span").text("失敗"); } } } ) }) </script> </body> </html>
向前端發送的是json格式的消息,因此在前端要用JSON.parse()來反序列化字符串爲JSON對象以後才能使用
views.py
from django.shortcuts import render,redirect,HttpResponse from app01 import models import json # Create your views here. def login(request): if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") print(username, password) ret = models.Userinfo.objects.filter(username=username,password=password) print(ret) a = {"status":None} if ret: a["status"] = True print(a) # {'status': True} msg = json.dumps(a) return HttpResponse(msg) else: return HttpResponse(a) else: return render(request,"login.html")
login.html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% csrf_token %} 用戶名: <input type="text" id="username"> 密碼: <input type="password" id="password"> <button id="sub">登錄</button> <span id="mag" style="color: red;font-size: 12px;"></span> <script src="{% static 'js/jquery.min.js' %}"></script> <script> $("#sub").click(function () { var uname = $("#username").val(); var pwd = $("#password").val(); var csrf_token = $("input[name=csrfmiddlewaretoken]").val(); $.ajax({ url:"{% url 'login' %}", type:"post", data:{"username":uname,"password":pwd,"csrfmiddlewaretoken":csrf_token}, success:function (response) { console.log(response, typeof response); msg = JSON.parse(response); if (msg.status){ $("span").text("登錄成功"); }else{ $("span").text("失敗"); } } } ) }) </script> </body> </html>
實現結果: