ajax(特色:異步請求和局部刷新)html
版本一:利用ajax作到局部刷新頁面向後端提交數據,前端接受後端返回的數據來選擇跳轉仍是添加頁面信息。 views: from django.shortcuts import render,HttpResponse # Create your views here. def login(request): if request.method=='GET': return render(request,'login.html') else: user = request.POST.get('username') pwd = request.POST.get('password') print(user,pwd) if user == 'liu' and pwd == '123': return HttpResponse('1') else: return HttpResponse('0') def home(request): return render(request,'home.html')
urls:前端
from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$',views.login,name='login'), url(r'^home/$',views.home,name='home'),
login.html:jquery
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 用戶名:<input type="text" id="username" > 密碼:<input type="password" id="password" > <button id="btn">提交</button> <span></span> </body> <script src="{% static 'jquery.js' %}"></script> <script> $('#btn').click(function () { var user = $('#username').val(); var pwd = $('#password').val(); console.log(user,pwd); $.ajax({ url:'{% url "login" %}', type:'post', data:{username:user,password:pwd}, success:function (res) { console.log(res,typeof res); if(res==='1'){ location.href = '/home/' }else{ $('span').text('用戶名或密碼錯誤') } } }) }) </script> </html>
home.html:ajax
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>day,day,up</h1> </body> </html>
csrftokendjango
2.1 原理:json
詳述CSRF(Cross-site request forgery),中文名稱:跨站請求僞造,也被稱爲:one click attack/session riding,縮寫爲:CSRF/XSRF。攻擊者經過HTTP請求江數據傳送到服務器,從而盜取回話的cookie。盜取回話cookie以後,攻擊者不只能夠獲取用戶的信息,還能夠修改該cookie關聯的帳戶信息。
因此解決csrf攻擊的最直接的辦法就是生成一個隨機的csrftoken值,保存在用戶的頁面上,每次請求都帶着這個值過來完成校驗。
https://blog.csdn.net/qq_42327755/article/details/80575565?tdsourcetag=s_pcqq_aiomsg後端
2.2 例證:瀏覽器
form表單經過csrf認證 login.html <form action="" method="post"> {% csrf_token %} 用戶名:<input type="text" name="username"> 密碼:<input type="password" name="password"> <input type="submit"> </form>
ajax經過csrf認證(三種方式) 第一種: <body> {% csrf_token %}-----瀏覽器渲染加上一個隱藏的input標籤 用戶名: <input type="text" id="username"> 密碼: <input type="password" id ='password'> <button id="btn">提交</button> <span></span> </body> <script src="{% static 'js/jquery.js' %}"></script> <script> $('#btn').click(function () { var user = $('#username').val(); var pwd = $('#password').val(); var csrf = $('[name=csrfmiddlewaretoken]').val();---獲取隱藏input標籤裏的value值 $.ajax({ url: '{% url "login" %}', type: 'post', data: {username: user, password: pwd,csrfmiddlewaretoken:csrf},---將數據添加上傳 success: function (res) { if (res === '1') { location.href = '/home/' } else { $('span').text('用戶名或密碼錯誤') } } }) }) </script>
第二種: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {#from表單經過csrf#} {#<form action="" method="post">#} {# {% csrf_token %}#} {# 用戶名:<input type="text" name="username">#} {# 密碼:<input type="password" name="password">#} {# <input type="submit">#} {#</form>#} {#{% csrf_token %}#} 用戶名: <input type="text" id="username"> 密碼: <input type="password" id ='password'> <button id="btn">提交</button> <span></span> </body> <script src="{% static 'js/jquery.js' %}"></script> <script> $('#btn').click(function () { var user = $('#username').val(); var pwd = $('#password').val(); {#var csrf = $('[name=csrfmiddlewaretoken]').val();#} var csrf = '{{ csrf_token }}';---{{變量}}瀏覽器直接將變量渲染成csrf_token值 {#var csrf = $('')#} $.ajax({ url: '{% url "login" %}', type: 'post', data: {username: user, password: pwd,csrfmiddlewaretoken:csrf}, success: function (res) { if (res === '1') { location.href = '/home/' } else { $('span').text('用戶名或密碼錯誤') } } }) }) </script> </html>
第三種: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 用戶名: <input type="text" id="username"> 密碼: <input type="password" id ='password'> <button id="btn">提交</button> <span></span> </body> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/jquery.cookie.js'%}"></script> <script> $('#btn').click(function () { var user = $('#username').val(); var pwd = $('#password').val(); $.ajax({ url: '{% url "login" %}', type: 'post', data: {username: user, password: pwd}, headers:{ "X-CSRFToken":$.cookie('csrftoken'), },----直接對cookie操做添加鍵值對便可 success: function (res) { if (res === '1') { location.href = '/home/' } else { $('span').text('用戶名或密碼錯誤') } } }) }) </script> </html>
上傳文件服務器
3.1 form表單上傳文件cookie
views: from django.shortcuts import render,HttpResponse,redirect from django.http import JsonResponse def upload(request): if request.method=='GET': return render(request,'upload.html') else: print(request.POST) print(request.FILES) file_obj = request.FILES.get('file') print(file_obj.name) with open(file_obj.name,'wb') as f: 第一種: for i in file_obj: f.write(i) 第二種:for chunk in file_obj.chunks():防止/r/n f.write(chunk) return HttpResponse('ok') upload.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} 用戶名:<input type="text" id="username"> 密碼:<input type="password" id = 'password'> <span></span> 頭像:<input type="file" name="file"> <input type="submit"> </form> </body> <script src="{% static 'js/jquery.js' %}"></script> </html>
3.2 ajax上傳文件
views: from django.conf import settings def upload(request): if request.method=='GET': return render(request,'upload.html') else: file_obj = request.FILES.get('file') with open(file_obj.name,'wb') as f: for chunk in file_obj.chunks(): f.write(chunk) return HttpResponse('ok') upload.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 用戶名:<input type="text" id="username"> 密碼:<input type="password" id = 'password'> 頭像:<input type="file"> <button id="stn">提交</button> </body> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/jquery.cookie.js' %}"></script> <script> $('#stn').click(function () { var formdata = new FormData(); var user = $('#username').val(); var pwd = $('#password').val(); var file_obj = $('[type=file]')[0].files[0]; formdata.append('user',user); formdata.append('pwd',pwd); formdata.append('file',file_obj); $.ajax({ url:'{% url "upload" %}', type:'post', data:formdata, headers:{ "X-CSRFToken":$.cookie('csrftoken'), }, processData:false, contentType:false, success:function (res) { console.log(res) } }) }) </script> </html>
jsonresponse
from django.http import JsonResponse username = request.POST.get('username') pwd = request.POST.get('password') ret_data = {'status':None,'msg':None} print('>>>>>',request.POST) #<QueryDict: {'{"username":"123","password":"123"}': ['']}> if username == 'chao' and pwd == '123': ret_data['status'] = 1000 # 狀態碼 ret_data['msg'] = '登陸成功' else: ret_data['status'] = 1001 # 狀態碼 ret_data['msg'] = '登陸失敗' # ret_data_json = json.dumps(ret_data,ensure_ascii=False) # return HttpResponse(ret_data_json,content_type='application/json') return JsonResponse(ret_data)---作了上面兩句話所作的事情
$.ajax({ url:'{% url "jsontest" %}', type:'post', // data:{username:uname,password:pwd,csrfmiddlewaretoken:csrf}, //data:JSON.stringify({username:uname,password:pwd}), data:{username:uname,password:pwd}, headers:{ // contentType:'application/json', "X-CSRFToken":$.cookie('csrftoken'), }, success:function (res) { {#console.log(res,typeof res); // statusmsg {"status": 1001, "msg": "登陸失敗"}#} {#var res = JSON.parse(res); //-- json.loads()#} console.log(res,typeof res); //直接就是反序列化以後的了 //JSON.stringify() -- json.dumps if (res.status === 1000){ // $('.error').text('登陸成功'); location.href = '/home/'; // http://127.0.0.1:8000/home/ }else{ $('.error').text(res.msg); } } })