1. 向服务器发送请求的途径
1.浏览器地址,默认get请求
2.form表单:
get请求
post请求
3.a标签,默认get请求
特点:
1.异步请求
2.局部刷新
AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。
-
同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
-
异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)
优点:
-
AJAX使用Javascript技术向服务器发送异步请求
-
AJAX无须刷新整个页面
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>index</title> </head> <body><h2>This is index!</h2><button class="Ajax">Ajex</button> <p class="content"></p><hr> <input type="text" id="num1"> + <input type="text" id="num2"> = <input type="text" id="ret"> <button class="cal">计算</button><hr><form> <!-- form都可以不用,但一般来说还是把表单标签放到form里面 -->用户名 <input type="text" id="user">密码 <input type="password" id="pwd"><input type="button" value="submit" class="login_btn"> <!-- 不能用submit,用submit就是form表单发请求了,不是ajax --><span class="error"></span> </form><script src="/static/jquery-3.3.1.js"></script><script>// 发送Ajax请求 $(".Ajax").click(function () {// 发送Ajax请求 $.ajax({url: '/test_ajax/', // 请求url type: 'get', // 或post data: {a: 1, b: 2},success: function (data) { // 回调函数:某个时间完成之后再去执行的函数 $(".content").text(data)}})});// Ajax计算求值 $('.cal').click(function () {let num1 = $('#num1').val();let num2 = $('#num2').val();$.ajax({url: '/cal/',type: 'post',data: {'n1': num1,'n2': num2,},success: function (data) { // 请求结果交给success函数 $('#ret').val(data);}})});// 登陆验证 $('.login_btn').click(function () {let user = $('#user').val();let pwd = $('#pwd').val();$.ajax({url: "/login/",type: 'post',data: {"username": user,"pwd": pwd,},success: function (data) {console.log(data); // json字符串 let parsed_data = JSON.parse(data); // 反序列化成 object类型 {}。 如果传的是列表就反序列化成数组类型if (parsed_data.user) {location.href = 'https://www.baidu.com'} else {$('.error').html(parsed_data.msg).css({'color':'red','margin-left':'10px'});}}})});</script> </body> </html>
views.py
from django.shortcuts import render, HttpResponse # Create your views here.from app01.models import User import jsondef index(request):return render(request, 'index.html')def test_ajax(request):print(request.GET)return HttpResponse('hello edward')def cal(request):n1 = int(request.POST.get('n1'))n2 = int(request.POST.get('n2'))ret = n1 + n2return HttpResponse(ret)def login(request):username = request.POST.get('username')pwd = request.POST.get('pwd')user = User.objects.filter(username=username, pwd=pwd).first()res = {'user': None, 'msg': None}if user:res['user'] = user.usernameelse:res['msg'] = 'username or password wrong!'return HttpResponse(json.dumps(res))
基于form表单的文件上传
html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>file put</title> </head> <body> <form action="" method="post" enctype="multipart/form-data">用户名 <input type="text" name="user">头像 <input type="file" name="avatar"><input type="submit"> </form> </body>
views.py
def file_put(request):if request.method == 'POST':print(request.POST)print(request.FILES) # 文件对象 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')return render(request, 'file_put.html')
<h3>简单的form</h3> <!-- 默认请求头是 "application/x-www-form-urlencoded" --> <form action="" method="post" enctype="application/x-www-form-urlencoded">用户名 <input type="text" name="user">密码 <input type="password" name="pwd"> </form><h3>基于form表单的文件上传</h3><!-- 请求头 multipart/form-data --> <form action="" method="post" enctype="multipart/form-data">用户名 <input type="text" name="user">头像 <input type="file" name="avatar"><input type="submit"> </form><h3>基于Ajax文件上传</h3><form action="" method="post">用户名 <input type="text"><input type="button" class="btn" value="Ajax"> </form><script>$('.btn').click(function () { // 还未实现,只是说明ajax不是用multipart/form-data上传文件的 $.ajax({url:'',type:'post',data:{ // 请求头默认也是application/x-www-form-urlencoded a:1,b:2},success:function () {console.log(data)}})}) </script>
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>file put</title> </head> <body> <h3>基于Ajax文件上传</h3><form action="" method="post">用户名 <input type="text"><input type="button" class="btn" value="Ajax"> </form><script src="/static/jquery-3.3.1.js"></script><script>$('.btn').click(function () {$.ajax({url:'',type:'post',contentType:'application/json',data:JSON.stringify({a:1,b:2}),success:function () {console.log(data)}})}) </script> </body> </html>
views.py
def file_put(request):if request.method == 'POST':print('body', request.body) # 请求报文中的请求体 body b'{"a":1,"b":2}'print('post', request.POST) # if contentType==urlencoded,request.POST才有数据。如果是urlencoded,那就把数据转换成字典,方便取值 post。此次传送的是json数据,所以没有值。 <QueryDict: {}>return HttpResponse('OK')return render(request, 'file_put.html')
基于Ajax的文件上传
html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>file put</title> </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="Ajax"> </form><script src="/static/jquery-3.3.1.js"></script><script>$('.btn').click(function () {let formdata = new FormData();let user = $('#user').val();let avatar = $('#avatar')[0].files[0];formdata.append("user", user);formdata.append('avatar', avatar);$.ajax({url: '',type: 'post',contentType: false, // 不做任何编码processData: false, // 不到预处理data: formdata,success: function (data) {console.log(data)}})}) </script> </body> </html>
views.py
def file_put(request):if request.method == 'POST':print('post', request.POST)print('file',request.FILES)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')return render(request, 'file_put.html')