login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% csrf_token %} <input type="text"id="username"> <input type="password" id="pwd" > <input type="button" id="b1" value="ajax登录校验"> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/init_ajax_csrftoken.js"></script> <script> $("#b1").on("click",function () { var username=$("#username").val(); var pwd=$("#pwd").val(); $.ajax({ url:"/login/", type:"POST", data:{"username":username,"pwd":pwd}, success:function (arg) { {#alert(arg)#} {#var ret=JSON.parse(arg)#} if (arg.status === 1) { location.href="http://www.baidu.com" }else{ alert(arg.msg) } } }) }) </script> </body> </html>
<script> $(".login_btn").on("click",function () { $.ajax({ url:"", type:"post", data:{ csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(), user:$("#user").val(), pwd:$("#pwd").val(), valid_code:$("#valid_code").val(), }, success:function (data) { console.log(data) if (data.state){ location.href="/index/" } else{ $(".error").text(data.msg) } } }) }) </script>
<span class="error" style="color: red;margin-left: 20px"></span>
ajax提交的数据使用的formdata 里面的k 应该和form组件内的k一样,除非不校验 例如 图片
<h3>Ajax上传文件</h3> <p><input type="text" name="username" id="username" placeholder="username"></p> <p><input type="file" name="upload_file_ajax" id="upload_file_ajax"></p> <button id="upload_button">提交</button> {#注意button标签不要用在form表单中使用#} <script> $("#upload_button").click(function(){ var username=$("#username").val(); var upload_file=$("#upload_file_ajax")[0].files[0]; var formData=new FormData(); formData.append("username",username); formData.append("upload_file_ajax",upload_file); $.ajax({ url:"/upload_file/", type:"POST", data:formData, contentType:false, processData:false, success:function(){ alert("上传成功!") } }); }) </script>
processData设置为false。因为data值是FormData对象,不需要对数据做处理。 <form>标签添加enctype="multipart/form-data"属性。 cache设置为false,上传文件不需要缓存。 contentType设置为false。因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false。
views.py
from django.shortcuts import render,HttpResponse,redirect import json from django.http import JsonResponse def login(request): if request.method == "POST": username=request.POST.get("username") # print(username) pwd=request.POST.get("pwd") # print(pwd) if username == "alex" and pwd == "123": ret={"status":1,"msg":"登陆成功"} else: ret={"status":0,"msg":"用户名或者密码错误!"} # json_ret=json.dumps(ret) # return HttpResponse(json_ret) from django.http import JsonResponse return JsonResponse(ret) return render(request,"login.html")
def login(request): if request.is_ajax(): user=request.POST.get("user") pwd=request.POST.get("pwd") valid_code=request.POST.get("valid_code") res={"state":False,"msg":None} valid_str=request.session.get("valid_str") if valid_code.upper() == valid_str.upper(): user=auth.authenticate(username=user,password=pwd) if user: res["state"]=True auth.login(request,user) else: res["msg"]="userinfo or pwd error" else: res["msg"]="验证码错误" return JsonResponse(res) return render(request,"login.html")
from django.contrib import auth from django.contrib.auth import authenticate, login
def index(request): return render(request,"index.html") def upload_file(request): print("FILES:",request.FILES) print("POST:",request.POST) return HttpResponse("上传成功!")
init_ajax_csrftoken.js (AJAX请求如何设置csrf_token,放入static,然后在html中导入)
// 从COokie取CSRF TOKEN的值 function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); // 将CSRF TOKEN值 设置到AJAX的请求头中,后续的AJAX请求就会自动携带这个CSRF TOKEN function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } });