AJAX(Asynchronous Javascript And Xml--异步Javascript和XML。)
是使用javascript语言与服务器进行异步交互,传输的数据不止为XML,使用更多的是json数据。
同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求。
异步请求:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
Ajax特点:
1.使用javascript技术向服务器发送异步请求。
2.局部页面刷新。
1.application/x-www-form-urlencoded
这是POST提交默认的方式。form表单如果不设置enctype属性,那么会以application/x-www-form-urlencoded方式提交数据。
2.multipart/form-data
使用表单上传文件时,form表单的enctype一定要是multipart/form-data
3.application/json
告诉服务端消息主体是序列化后的JSON字符串。
浏览器端序列化JSON的方法JSON.stringify(),反序列化的方法JSON.parse()。
json格式支持多种结构化的数据。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<input type="button" value="AJAX_GET" id="ajax_get">
</body>
<script type="text/javascript">
$("#ajax_get").click(
function () {
$.ajax({
url:"/ajax_get/",
type:"get",
data:{
a:1,
b:2
},
success:function (data) {
console.log(data)
}
})
}
)
</script>
</html>
views.py
from django.shortcuts import render,HttpResponse
def index(request):
return render(request, "index.html")
def ajax_get(request):
# ajax中的数据放置在request.GET中,通过request.GET.get("a")获取数据
print(request.GET) # <QueryDict: {‘a‘: [‘1‘], ‘b‘: [‘2‘]}>
print(type(request.GET)) # <class ‘django.http.request.QueryDict‘>
print(request.GET.get("a")) # 1
print(request.GET.get("b")) # 2
return HttpResponse("ajax_get")
urls.py
from django.contrib import admin
from django.urls import path, register_converter
from app1 import views,converters
register_converter(converters.YearConverter,"int_con")
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path("index/", views.index),
path("ajax_get/", views.ajax_get),
]
print(request.body) # b‘a=1&b=2‘,请求报文中的请求体,只有post请求时,请求体中才有内容
print(request.POST) # <QueryDict: {‘a‘: [‘1‘], ‘b‘: [‘2‘]}>,只有contentType==urlencoded(默认是urlencode)时,request.POST才有值
# 虽然request.body中有内容,但是不方便获取值,需要自己手动进行解析,所以在默认contentType下,都使用request.POST方式获取值。
# 当contentType:"application/json"时,request.POST中无数据,可以取request.body中的值,然后json.loads()解析。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<input type="text" id="n1">+<input type="text" id="n2">=<input type="text" id="n3">
<input type="button" value="cal" id="ajax_post">
</body>
<script type="text/javascript">
$("#ajax_post").click(
function () {
$.ajax({
url:"/ajax_post/",
type:"post",
data:{
a:$("#n1").val(),
b:$("#n2").val()
},
success:function (data) {
{#给第三个input框设置值#}
$("#n3").val(data)
}
})
}
)
</script>
</html>
views.py
from django.shortcuts import render,HttpResponse
def index(request):
return render(request, "index.html")
def ajax_post(request):
print(request.body) # b‘a=1&b=2‘,请求报文中的请求体,只有post请求时,请求体中才有内容
print(request.POST) # <QueryDict: {‘a‘: [‘1‘], ‘b‘: [‘2‘]}>,只有contentType==urlencoded(默认是urlencode)时,request.POST才有值
# 虽然request.body中有内容,但是不方便获取值,需要自己手动进行解析,所以在默认contentType下,都使用request.POST方式获取值。
a = int(request.POST.get("a"))
b = int(request.POST.get("b"))
ret = a+b
return HttpResponse(ret)
urls.py
from django.contrib import admin
from django.urls import path, register_converter
from app1 import views,converters
register_converter(converters.YearConverter,"int_con")
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path("index/", views.index),
path("ajax_post/", views.ajax_post),
]
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<form>
用户名 <input type="text" id="user">
密码 <input type="password" id="pwd">
<input type="button" value="submit" class="login_btn"><span class="error"></span>
</form>
</body>
<script type="text/javascript">
$(".login_btn").click(
function () {
$.ajax({
url:"/login/",
type:"post",
contentType:"application/json",//发送接送数据的时候,格式一定要是contentType:"application/json"
data:JSON.stringify({
user:$("#user").val(),
pwd:$("#pwd").val()
}),
success:function (data) {
console.log(data);//json字符串,{"user": "vita", "msg": null}
console.log(typeof(data)); //string
{#解析views.py中传过来的json数据#}
let par_data = JSON.parse(data);
console.log(par_data);//{user: "vita", msg: null}
console.log(typeof(par_data));//object
if(par_data.user){
console.log(par_data.user)//vita
}else {
$(".error").html(par_data.msg).css("color","red")
}
}
})
}
)
</script>
</html>
views.py
from django.shortcuts import render,HttpResponse
import json
def index(request):
return render(request, "index.html")
def login(request):
print("request.body----", request.body) # b‘{"user":"vita","pwd":"123"}‘只能从request.body中获取数据
print("request.POST----", request.POST) # <QueryDict: {}>,contentType:"application/json"----此时request.POST中无数据
data = json.loads(request.body) # 反序列化json数据
print(data) # {‘user‘: ‘vita‘, ‘pwd‘: ‘123‘}
print(type(data)) # <class ‘dict‘>
user = data.get("user")
pwd = data.get("pwd")
res = {"user": None, "msg": None}
if user == "vita" and pwd == "123":
res["user"] = user
else:
res["msg"] = "username or password is not correct!"
# 转换为json字符串,发送到前端
return HttpResponse(json.dumps(res))
urls.py
from django.contrib import admin
from django.urls import path, register_converter
from app1 import views,converters
register_converter(converters.YearConverter,"int_con")
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path("index/", views.index),
path("login/", views.login),
]
views.py中
json.dumps(res)
html中
JSON.parse()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<form>
用户名 <input type="text" id="user">
密码 <input type="password" id="pwd">
<input type="button" value="submit" class="login_btn"><span class="error"></span>
</form>
</body>
<script type="text/javascript">
$(".login_btn").click(
function () {
$.ajax({
url:"/login/",
type:"post",
data:{
user:$("#user").val(),
pwd:$("#pwd").val()
},
success:function (data) {
console.log(data);//json字符串,{"user": "vita", "msg": null}
console.log(typeof(data)); //string
{#解析views.py中传过来的json数据#}
let par_data = JSON.parse(data);
console.log(par_data);//{user: "vita", msg: null}
console.log(typeof(par_data));//object
if(par_data.user){
console.log(par_data.user)//vita
}else {
$(".error").html(par_data.msg).css("color","red")
}
}
})
}
)
</script>
</html>
views.py
from django.shortcuts import render,HttpResponse
import json
def index(request):
return render(request, "index.html")
def login(request):
user = request.POST.get("user")
pwd = request.POST.get("pwd")
res = {"user":None,"msg":None}
if user=="vita" and pwd=="123":
res["user"]=user
else:
res["msg"]="username or password is not correct!"
# 转换为json字符串,发送到前端
return HttpResponse(json.dumps(res))
urls.py
from django.contrib import admin
from django.urls import path, register_converter
from app1 import views,converters
register_converter(converters.YearConverter,"int_con")
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path("index/", views.index),
path("login/", views.login),
]
"request.FILES对象获取文件的相关内容"
print("request.POST----", request.POST) # request.POST---- <QueryDict: {‘user‘: [‘vita‘]}>
print("request.FILES----", request.FILES) # request.FILES---- <MultiValueDict: {‘avatar‘: [<InMemoryUploadedFile: baby.jpg (image/jpeg)>]}>
if request.method == "POST":
file_obj = request.FILES.get("avatar")
with open(file_obj.name, "wb") as f:
for line in file_obj:
f.write(line)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<h3>基于form表单的文件上传</h3>
<form action="/login/" method="post" enctype="multipart/form-data">
用户名<input type="text" name="user"><!--这里是根据name来获取key的-->
头像 <input type="file" name="avatar">
<input type="submit">
</form>
</body>
<script type="text/javascript">
</script>
</html>
views.py
from django.shortcuts import render,HttpResponse
import json
def index(request):
return render(request, "index.html")
def login(request):
print("request.body----", request.body)
print("request.POST----", request.POST) # request.POST---- <QueryDict: {‘user‘: [‘vita‘]}>
print("request.FILES----", request.FILES) # request.FILES---- <MultiValueDict: {‘avatar‘: [<InMemoryUploadedFile: baby.jpg (image/jpeg)>]}>
if request.method == "POST":
file_obj = request.FILES.get("avatar") # 这里是html中input的name
with open(file_obj.name, "wb") as f:
for line in file_obj:
f.write(line)
return HttpResponse("OK")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<h3>基于ajax文件上传</h3>
<form action="" method="post">
用户名<input type="text" id="user">
头像 <input type="file" id="avatar">
<input type="button" class="btn" value="提交">
</form>
</body>
<script type="text/javascript">
$(".btn").click(function () {
let formdata = new FormData();
formdata.append("user",$("#user").val());
console.log("$(\"#avatar\")[0]----",$("#avatar")[0]);
console.log("$(\"#avatar\")[0].files----",$("#avatar")[0].files);
console.log("$(\"#avatar\")[0].files[0]----",$("#avatar")[0].files[0]);
formdata.append("avatar",$("#avatar")[0].files[0]);
$.ajax({
url:"/login/",
type:"post",
data:formdata,
contentType:false,// 不处理数据
processData:false,// 不设置内容类型
success:function (data) {
console.log(data)
}
})
})
</script>
</html>
views.py
from django.shortcuts import render,HttpResponse
import json
def index(request):
return render(request, "index.html")
def login(request):
print("request.body----", request.body)
print("request.POST----", request.POST) # request.POST---- <QueryDict: {‘user‘: [‘vita‘]}>
print("request.FILES----", request.FILES) # request.FILES---- <MultiValueDict: {‘avatar‘: [<InMemoryUploadedFile: baby.jpg (image/jpeg)>]}>
if request.method == "POST":
file_obj = request.FILES.get("avatar")
with open(file_obj.name, "wb") as f:
for line in file_obj:
f.write(line)
return HttpResponse("OK")
原文:https://blog.51cto.com/10983441/2414550