from django.shortcuts import render from django.http import JsonResponse # 针对ajax设置csrf_token from django.views.decorators.csrf import csrf_protect, csrf_exempt def index(request): return render(request, "index.html") @csrf_exempt def handle_ajax(request): if request.method == ‘POST‘: user_name = request.POST.get("username", "") pass_word = request.POST.get("password", "") print(user_name, pass_word) if user_name == pass_word: return JsonResponse({"ret":1}) else: return JsonResponse({"ret":2})
<head> <meta charset="UTF-8"> <title>Title</title> <script src="{% static ‘js/jquery-3.2.1.js‘ %}"></script> </head> <body> <h1>ajax的发送异步请求</h1> <button class="send_Ajax">Post发送请求</button> <!-- jquery实现ajax发送post请求--> <script> // 选取标签,执行点击事件 $(".send_Ajax").click(function(){ $.ajax({ url:"/handle/", type:"POST", data:{username:123,password:123}, success:function(data){ if(data.ret==1){ alert("用户名等于密码!") }else{ alert("用户名不等于密码!") } } }); }) </script> </body> </html>