AJAX
(Asynchronous Javascript And XML)——「異步的JavaScript與XML」。css
Ajax使用Javascript語言與服務器進行異步的交互,傳輸的數據爲XML(時至今日,傳輸的數據更多爲Json格式)。html
同步交互與異步交互python
同步交互:客戶端發出一個請求後,須要等待服務器響應結束後,才能發出第二個請求;jquery
異步交互:客戶端發出一個請求後,無需等待服務器響應結束,就能夠發出第二個請求。ajax
Ajax的特色:django
Ajax的優勢:json
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"> </script> </head> <body> <div class="content"></div> <button class="Ajax">Ajax</button> <script> $(".Ajax").click(function () { $.ajax({ url: '/test/', type: 'get', success: function (data) { $('.content').html(data) } } ) }) </script> </body> </html>
from django.shortcuts import render,HttpResponse # Create your views here. def index(request): return render(request,'index.html') def test(request): return HttpResponse('hello Ajax')
實現效果:瀏覽器
<input type="text" id="num1">+<input type="text" id="num2">=<input type="text" id="ret"><button class="cal">計算</button> $('.cal').click(function () { $.ajax({ url:'/cal/', type:'post', data:{ 'n1':$('#num1').val(), 'n2':$('#num2').val(), }, success:function (data) { console.log(data); $('#ret').val(data); } }) })
def cal(request): print(request.POST) n1 = int(request.POST.get('n1')) n2 = int(request.POST.get('n2')) ret = n1+n2 return HttpResponse(ret)
實現效果:服務器
<form > 用戶名 <input type="text" id="user"> 密碼 <input type="password" id="pwd"> <input type="button" value="submit" class="login_btn"><span class="error"></span> </form> $('.login_btn').click(function () { $.ajax({ url:"/login/", type:'post', data:{ 'user':$('#user').val(), 'pwd':$('#pwd').val(), }, success:function(data){ console.log(data); console.log(typeof data); var data=JSON.parse(data); console.log(data); console.log(typeof data); if (data.user){ location.href='http://www.baidu.com' } else { $(".error").html(data.msg).css({"color":'red',"margin-left":'10px'}) } } }) })
def login(request): print(request.POST) user=request.POST.get("user") pwd=request.POST.get('pwd') user= User.objects.filter(name=user,pwd=pwd).first() res= {"user":None,"msg":None} if user: res["user"] = user.name else: res["msg"]= "username or password wrong!" import json return HttpResponse(json.dumps(res))