Django -Ajax
Ajax
特點(diǎn)優(yōu)勢(shì):
- 異步請(qǐng)求
- 局部刷新
常用參數(shù):
- URL:請(qǐng)求路徑,為空則默認(rèn)為腳本所在路徑
- type:請(qǐng)求方式,get和post
- data:數(shù)據(jù),可自定義數(shù)據(jù)格式
- contentType:數(shù)據(jù)編碼格式
- processData:數(shù)據(jù)是否預(yù)處理
- sucess:function({data){}:回調(diào)函數(shù),處理前端返回的數(shù)據(jù)
$(".btn").click(function () {
$.ajax({
url:"",
type:"post",
data:"",
contentType:'',
processData: '',
success:function (data) {
}
})
})
自定義數(shù)據(jù)格式:
將data中的數(shù)據(jù)以Json的格式傳遞
- JSON.stringify:序列化字符串
- JSON.parse:反序列化字符串
$(".btn").click(function () {
$.ajax({
url:"",
type:"post",
data:JSON.stringify({"a":1,"b":2}), # 使用jQuery的 JSON序列化
contentType:'',
processData: '',
success:function (data) {
console.log(data)
}
})
})
Ajax表單登錄驗(yàn)證
視圖函數(shù)處理:
def login(request):
state = {"user":None,"msg":""}
user =request.POST.get("user")
pwd =request.POST.get("pwd")
user = User.objects.filter(user=user,pwd=pwd).first()
if user:
state["user"] = user.user
else:
state["msg"] = "wrong"
return HttpResponse(json.dumps(state))
HTML文件:
<h1>Ajax表單的登錄驗(yàn)證</h1>
<form>
user:<input type="text" id="user">
pwd:<input type="password" id="pwd">
<input type="button" id="ajax_login" value="ajax">
<span class="error"></span>
</form>
<script>
$("#ajax_login").click(function () {
$.ajax({
url: "/login/",
data: {
"user":$("#user").val(),
"pwd":$("#pwd").val(),
},
type: "post",
success:function (data) {
console.log(data); // {"user": "tom", "msg": ""}
console.log(typeof data); //str類(lèi)型
var data = JSON.parse(data); // 將json字符串轉(zhuǎn)為jQuery的數(shù)據(jù)格式
console.log(typeof data); // obj類(lèi)型
if (data.user){
location.
}
else {
$(".error").html(data.msg).css({"color":"red","magain-ringt":"10px"})
}
}
})
})
Ajax傳輸鍵值對(duì)數(shù)據(jù):
<form enctype="multipart/form-data" >
用戶(hù)名:<input type="text" id="name" >
頭 像:<input type="file" id="files" >
<input type="button" class="btn" value="ajax">
</form>
<script>
$(".btn").click(function () {
$.ajax({
url:"",
type:"post",
data:{
"name":$("#name").val(),
"files":$("#files").val(),
},
success:function (data) {
console.log(data)
}
})
})
</script>
處理函數(shù)打印結(jié)果:
body: b'name=Tom&files=C%3A%5Cfakepath%5C%E6%9D%A8%E5%B9%823.jpg'
post: <QueryDict: {'name': ['Tom'], 'files': ['C:\\fakepath\\楊冪3.jpg']}>
在請(qǐng)求頭Form Data中即可看到數(shù)據(jù):

Ajax文件傳輸:
Ajax傳輸文件需要先創(chuàng)建 “FormData“,然后根據(jù)導(dǎo)入 數(shù)據(jù) formdata.append("",""); # 以鍵值對(duì)的形式導(dǎo)入
var formdata =new FormData();
formdata.append("name",$("#name").val());
formdata.append("files",$("#files")[0].files[0]);
HTML文件:
<h1>Ajax表單上傳文件</h1>
<form >
用戶(hù)名:<input type="text" id="name" >
頭 像:<input type="file" id="files" >
<input type="button" class="btn" value="ajax">
</form>
<script>
$(".btn").click(function () {
var formdata =new FormData();
formdata.append("name",$("#name").val());
formdata.append("files",$("#files")[0].files[0]);
$.ajax({
url:"",
type:"post",
contentType: false,
processData: false,
data:formdata,
success:function (data) {
console.log(data)
}
})
})
</script>
其中, $("#files")[0].files[0] 是獲取Jquery獲取文件的固定格式
函數(shù)處理:
if request.method == "POST":
files = request.FILES.get("files") # 獲取文件
with open(files.name,"wb") as f:
for line in files:
f.write(line)
return HttpResponse("ok")
return render(request,"upfiles.html")
擴(kuò)展:POST、body,F(xiàn)ILES
打印上面的示例
print("body:",request.body)
# 只要報(bào)文的請(qǐng)求體中有值,body里就會(huì)有數(shù)據(jù)
print("post:",request.POST) # post: <QueryDict: {'name': ['Tom']}> 編碼為encod時(shí) 才會(huì)講body中的bety數(shù)據(jù)類(lèi)型轉(zhuǎn)為字典 以方便獲取值 print("FILES:",request.FILES) # FILES: <MultiValueDict: {'files': [<InMemoryUploadedFile: 楊冪4.jpg (image/jpeg)>]}> # 只有在傳輸文件時(shí)才有值

浙公網(wǎng)安備 33010602011771號(hào)