ajax(Asynchronous Javascript And Xml) 异步javascript和XML
ajax的优点
使用javascript技术向服务器发送异步请求
ajax无须刷新整个页面;
由于ajax响应的是局部页面,因此性能要高
当以get的方式向服务器发送请求:
views.py
def user_valid(request):
name=request.GET.get("name")
ret=Author.objects.filter(name=name)
res={"state":True,"msg":""}
if ret:
res["state"]=False
res["msg"]="用户存在"
import json
return HttpResponse(json.dumps(res)) #向ajax发送json数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>ajax请求</p> <button class="s1">send_ajax</button> <p class="con"></p> <hr><p>用户名:<input type="text" id="user"><span class="error"></span></p> <script src="/static/js/jquery-3.3.1.min.js"> </script> <script> $(".s1").click(function(){ $.ajax({ url:"/send_ajax/", type:"get", data:{}, success:function(data){ $(".con").html(data) } }) }); $("#user").blur(function () { //鼠标失去焦点事件 $.ajax({ url: "/user_valid/", type: "get", data: {"name": $("#user").val()}, success: function (data) { console.log(data); console.log(typeof data); var data = JSON.parse(data); //接收传来的信息,进行反序列化,这里JSON要输入大写否则出不来 console.log(data); console.log(typeof data); if (!data.state) { $(".error").html(data.msg).css("color", "red") #这里的css样式是以,隔开的 } } }) });</script> </body> </html>
下面是以post的方式提交,并且跨域伪造csrf的方式(三种)
def user_valid(request):
name = request.POST.get("name")
ret=Author.objects.filter(name=name)
res={"state":True,"msg":""}
if ret:
res["state"]=False
res["msg"]="用户存在"
import json
return HttpResponse(json.dumps(res))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>ajax请求</p> <button class="s1">send_ajax</button> <p class="con"></p> <hr> {% csrf_token %} #方式一 <p>用户名:<input type="text" id="user"><span class="error"></span></p> <script src="/static/js/jquery-3.3.1.min.js"> </script> <script> $(".s1").click(function(){ $.ajax({ url:"/send_ajax/", type:"get", data:{}, success:function(data){ $(".con").html(data) } }) }); //下面改成post请求如何避免crsf错误呢 $("#user").blur(function () { $.ajax({ url: "/user_valid/", type: "post", data: {"name": $("#user").val(), "csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val(), //方式二
headers:{"X-CSRFToken":$.cookie('csrftoken')}, //方式三 },
success: function (data) { console.log(data); console.log(typeof data); var data = JSON.parse(data); console.log(data); console.log(typeof data); if (!data.state) { $(".error").html(data.msg).css("color", "red") } } }) }); </script> </body> </html>
下面是效果
如何不用上面的方式,也可以通过csrf中的csrf_exempt 的方法排除验证csrf
方式一:在views.py里面修改
#urls.py里面
url(r'^login/$',views.LoginView.as_view()),
#views.py
from django.shortcuts import render,HttpResponse,redirect
from django.views.decorators.csrf import csrf_exempt #导入
# Create your views here.
from rbac.models import UserInfo
from django.views import View
class LoginView(View):
def get(self,request):
return render(request,"login.html")
def post(self,request):
user=request.POST.get("user")
pwd=request.POST.get("pwd")
user=UserInfo.objects.filter(name=user,pwd=pwd).first()
print(user,user.pk)
if user:
request.session["user_id"]=user.pk
#将用户的权限注册到session中
permission_list=[]
ret=user.roles.all().values("permissions__url").distinct()
for per in ret:
permission_list.append(per.get("permissions__url"))
# print(ret)
request.session["permission_list"]=permission_list
return HttpResponse("ok")
return HttpResponse("用户名或密码错误")
@csrf_exempt #当继承django里面的类时,必须要写一个dispath方式,并写在它上面
def dispatch(self,*args,**kwargs):
# return super(LoginView,self).dispatch(*args,**kwargs) #这两个方法都可以
return super().dispatch(*args, **kwargs)
方式二:加入到urls里面
# urls
from django.views.decorators.csrf import csrf_exempt
url(r'^login/$',csrf_exempt(views.LoginView.as_view())), #加入到urls里面
#views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from rbac.models import UserInfo
from django.views import View
class LoginView(View):
def get(self,request):
return render(request,"login.html")
def post(self,request):
user=request.POST.get("user")
pwd=request.POST.get("pwd")
user=UserInfo.objects.filter(name=user,pwd=pwd).first()
print(user,user.pk)
if user:
request.session["user_id"]=user.pk
#将用户的权限注册到session中
permission_list=[]
ret=user.roles.all().values("permissions__url").distinct()
for per in ret:
permission_list.append(per.get("permissions__url"))
# print(ret)
request.session["permission_list"]=permission_list
return HttpResponse("ok")
return HttpResponse("用户名或密码错误")
ajax处理json数据
1 我们在views里面向ajax发送一个json数据
def send_ajax(request):
import json
return HttpResponse(json.dumps({"name":"xinxin"}))
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>ajax请求</p>
<button class="s1">send_ajax</button>
<p class="con"></p>
<hr>
{% csrf_token %}
<p>用户名:<input type="text" id="user"><span class="error"></span></p>
<script src="/static/js/jquery-3.3.1.min.js">
</script>
<script>
//没有指定dataType的情况
/* $(".s1").click(function(){
$.ajax({
url:"/send_ajax/",
success:function(data){
console.log(data); //{"name": "xinxin"}
console.log(typeof(data)); //string
}
})
});*/
//指定dataType的情况
$(".s1").click(function(){
$.ajax({
url:"/send_ajax/",
dataType:"json", //主要T要大写
success:function(data){
console.log(data); //Object {name: "xinxin"} 类型发生了变化
console.log(typeof(data)); // object
},
error:function(jqXHR,textStatus,err){
console.log(err);
console.log("数据错误。。。。。。。")
}
})
});
</script>
2 向ajax发送一个其他数据时
def send_ajax(request):
return HttpResponse("{'name':'xinxin'}")
#index.html
//指定dataType的情况
$(".s1").click(function(){
$.ajax({
url:"/send_ajax/",
dataType:"json", //主要T要大写
success:function(data){
console.log(data); //Object {name: "xinxin"} 类型发生了变化
console.log(typeof(data)); // object
},
error:function(jqXHR,textStatus,err){
console.log(err); //报错打印出错误信息
console.log("数据错误。。。。。。。") //制定错误信息
}
})
});