标签:blur lan static response ror send alt 效果 function
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); //接收传来的信息,进行反序列化 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>
下面是效果
标签:blur lan static response ror send alt 效果 function
原文地址:https://www.cnblogs.com/mmyy-blog/p/10512361.html