from django.shortcuts import renderfrom django.http import JsonResponse# 针对ajax设置csrf_tokenfrom django.views.decorators.csrf import csrf_protect, csrf_exemptdef index(request): ???return render(request, "index.html")@csrf_exemptdef 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>
简单的ajax请求处理 | Django
原文地址:http://www.cnblogs.com/pymkl/p/8046523.html