小白學Django-----------初識Ajax
阿新 • • 發佈:2018-11-27
Ajax
一.什麼是Ajax
AJAX(Asynchronous Javascript And XML),就是“非同步Javascript和XML”。即使用Javascript語言與伺服器進行非同步互動,傳輸的資料為XML(當然,傳輸的資料不只是XML,現在更多使用json資料)。
- 同步互動:客戶端發出一個請求後,需要等待伺服器響應結束後,才能發出第二個請求;
- 非同步互動:客戶端發出一個請求後,無需等待伺服器響應結束,就可以發出第二個請求。
AJAX除了非同步的特點外,還有一個就是:瀏覽器頁面區域性重新整理;(這一特點給使用者的感受是在不知不覺中完成請求和響應過程)
優點:
- AJAX使用Javascript技術向伺服器傳送非同步請求
- AJAX無須重新整理整個頁面
二.基於jquery的Ajax簡單實現
test1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
使用者名稱: < input type="text" name="user" id="user"> <br>
密碼: <input type="password" name="pwd" id="pwd"> <br>
<button>POST提交</button>
</form>
<button id="btn">Ajax提交</button>
</body>
<script src="/static/jquery/jquery-3.3.1.js"></script>
< script>
$('#btn').click(function () {
let user = $('#user').val();
let pwd = $('#pwd').val();
$.ajax({
url:'/test1/',
type:'get',
data:{'name':user,'pwd':pwd},
success:function (data) {
alert(data)
}
})
})
</script>
</html>
views.py
def test1(request):
user = request.GET.get('name')
pwd = request.GET.get('pwd')
if user == 'tom' and pwd == '123':
return HttpResponse('登入成功')
return HttpResponse('使用者名稱或密碼錯誤')
Ajax執行流程
根據ajax裡面的url匹配到views.py檔案裡面的檢視函式,然後發個請求(看type是什麼請求),然後檢視函式做一系列的處理,然後return給了ajax裡面的data。因為是非同步的,所以檢視函式處理時不影響ajax後面的程式碼執行。一旦有資料return時,執行success內的函式程式碼。
三.案例
3.1 通過Ajax,實現前端輸入兩個數字,伺服器做加法,返回到前端頁面
檢視函式
def test_ajax(requests):
n1=int(requests.POST.get('n1'))
n2=int(requests.POST.get('n2'))
return HttpResponse(n1+n2)
html程式碼
<input type="text" id="num1">+<input type="text" id="num2">=<input type="text" id="sum">
<button id="submit">計算</button>
JS程式碼
$("#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)
},
})
})
3.2 基於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.name
back_dic['message']='成功'
else:
back_dic['message']='使用者名稱或密碼錯誤'
import json
return HttpResponse(json.dumps(back_dic))
JS程式碼
$("#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'})
}
}
})
}
)
四.基於Ajax提交json格式資料(簡單版)
html+js程式碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
使用者名稱: <input type="text" name="user" id="user"> <br>
密碼: <input type="password" name="pwd" id="pwd"> <br>
<button>POST提交</button>
</form>
<button id="btn">Ajax提交</button>
</body>
<script src="/static/jquery/jquery-3.3.1.js"></script>
<script>
$('#btn').click(function () {
let user = $('#user').val();
let pwd = $('#pwd').val();
let s = JSON.stringify({'name':user,'pwd':pwd}); //json格式字串
let t = JSON.parse(s); //反轉回來
$.ajax({
url:'/test3/',
type:'post',
contentType:'application/json', //預設是urlencoded
data:s,
dataType:'json', //響應回來解析的方式
success:function (data) {
alert(data)
}
})
})
</script>
</html>
檢視函式
def test3(request):
if request.method == 'POST':
#只處理了urlencoding編碼的引數:name='tom'&pwd='123'
# 前端提交的json格式資料,需要自己處理
# 提交到伺服器的資料都在 request.body 裡,取出來自行處理
print(request.body)
import json
res = request.body.decode('utf-8')
res_dic = json.loads(res)
print('res_dic===>',res_dic)
if res_dic['name'] == 'tom' and res_dic['pwd'] == '123':
return HttpResponse('登入成功')
return HttpResponse('使用者名稱密碼錯誤')
五,基於Ajax簡單上傳檔案
html+js程式碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>檔案上傳</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
使用者名稱: <input type="text" name="user" id="user"> <br>
密碼: <input type="password" name="pwd" id="pwd"> <br>
檔案: <input type="file" name="myfile" id="myfile"> <br>
<button>提交</button>
</form>
<button id="btn">ajax提交</button>
</body>
<script src="/static/jquery/jquery-3.3.1.js"></script>
<script>
$('#btn').click(function () {
let formdata = new FormData(); //生成一個Formdata物件
formdata.append('myfile',$('#myfile')[0].files[0]);
formdata.append('name',$('#user').val());
formdata.append('pwd',$('#pwd').val());
$.ajax({
url:'/test4/',
type:'post',
contentType:false, //告訴jQuery不要去處理髮送的資料
processData:false, // 告訴jQuery不要去設定Content-Type請求頭
data:formdata,
success:function (data) {
alert(data)
}
})
})
</script>
</html>
檢視函式
def test4(request):
if request.method == 'POST':
name = request.POST.get('name')
pwd = request.POST.get('pwd')
file = request.FILES.get('myfile')
file_name = file.name
with open(file_name,'wb') as f:
for line in file:
f.write(line)
return HttpResponse('ok')