1 什么是ajax:
異步的JavaScript和xml,跟后台交互,都用json
2 ajax干啥用的?
前后端做數據交互:
3 特點:
-異步(異步和同步的區別:同步是請求發過去,要等着回應;異步:不需要等回應,可以進行其他操作)
-局部刷新:
4 使用ajax實現一個簡單的文件上傳頁面
前端頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/static/jquery-3.3.1.js"></script>
<title>Title</title>
</head>
<body>
<form action="/files/" method="post" enctype="multipart/form-data">
<p>用戶名:<input type="text" name="name" id="name"></p>
<p><input type="file" name="myfile" id="myfile"></p>
<input type="submit" value="提交">
</form>
<button id="btn">ajax提交文件</button>
</body>
<script>
$("#btn").click(function () {
//上傳文件,必須用FormData
var formdata=new FormData();
formdata.append('name',$("#name").val());
//取出文件$("#myfile")[0].files拿到的是文件列表,取第0個把具體的文件取出來
formdata.append('myfile',$("#myfile")[0].files[0]);
$.ajax({
url:'/files_ajax/',
type:'post',
//不預處理數據,(name=lqz&age=18)
processData:false,
//指定往后台傳數據的編碼格式(urlencoded,formdata,json)
//現在用formdata對象處理了,就不需要指定編碼格式了,不要給我編碼了
contentType:false,
data:formdata,
success:function (data) {
alert(data)
}
})
})
</script>
</html>
后台views.py中的頁面
def files_ajax(request):
# 提交文件從,request.FILES中取,提交的數據,從request.POST中取
name=request.POST.get('name')
print(name)
dic_files = request.FILES
myfile = dic_files.get('myfile')
with open(myfile.name, 'wb') as f:
# 循環上傳過來的文件
for line in myfile:
# 往空文件中寫
f.write(line)
return HttpResponse('ok')
5 基於ajax提交json格式的數據(簡單的用戶登錄認證)
前端頁面
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>登錄驗證</title>
<script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<form>
<p>用戶名:<input type="text" name="user" id="name"></p>
<p>密碼:<input type="password" name="pwd" id="pwd"></p>
</form>
<button id="btn">提交</button>
<p class="test"></p>
</body>
<script>
$('#btn').click(function () {
var dic = {'name':$('#name').val(),'pwd':$('#pwd').val()};
var msg = JSON.stringify(dic);
var $test = $('.test');
$.ajax({
url:'/login/',
type:'post',
//指定請求的數據格式為json
contentType:'application/json',
data:msg,
//指定響應的格式為json,注意如果后台沒有放回json類型的數據格式下方的success不會執行
dataType:'json',
success:function (res) {
data = JSON.parse(res);
if (data == '2'){
$test.text('登錄失敗!')
} else if (data == '1'){
location.href='https://www.baidu.com/'
}
}
});
});
</script>
</html>
后台views.py中的內容
from django.shortcuts import render, redirect, HttpResponse
import json
from loginapp.models import *
# Create your views here.
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == "POST":
msg = json.loads(request.body.decode('utf-8'))
print(msg)
res = User.objects.filter(user=msg['name'], pwd=msg['pwd']).first()
if res:
return HttpResponse(json.dumps('1'))
else:
return HttpResponse(json.dumps('2'))