原文:http://qindongliang.iteye.com/blog/2147336

Ajax的出现让Web展现了更新的活力,基本所有的语言,都动态支持Ajax与起服务端进行通信,并在页面实现无刷新动态交互。 


下面是散仙使用Django+Jquery+Ajax的方式来模拟实现了一个验证用户注册时,用户名存在不存在的一个小应用。注意,验证存在不存在使用的是Ajax的方式,不用让用户点击按钮验证是否存在。 

截图如下: 

django 接收ajax请求_django 接收ajax请求 

django 接收ajax请求_django 接收ajax请求_02 


页面HTML代码如下: 

Html代码  django 接收ajax请求_django 接收ajax请求_03

  1. <!DOCTYPE html>  

  2. <html>  

  3. <head lang="en">  

  4.     <meta charset="UTF-8">  

  5.     <title>Ajax验证测试</title>  

  6. </head>  

  7. <script src="/static/jquery/jquery211.js"></script>  

  8. <script>  

  9.   

  10.     $(function(){  

  11.   

  12.        $("#pu").bind('keydown',function(){  

  13.            c=$("#pu").val()  

  14.            $.ajax({  

  15.                 type:"POST",  

  16.                 url:"/ccc/",  

  17.                 data:{name:c},  

  18.                 dataType:"json",  

  19.                 success: function(data) {  

  20.                     $("#p").text(data.msg)  

  21.                 }  

  22.             });  

  23.   

  24.   

  25.        })  

  26.   

  27.     })  

  28.   

  29.   

  30. </script>  

  31. <body>  

  32.   

  33.   

  34.   

  35. 输入名字进行校验:<input id="pu" type="text"> <span id="p" style="color: red"></span>  

  36.   

  37. </body>  

  38. </html>  




view端的代码,注意csrf的装饰方法,针对post请求: 

Python代码  django 接收ajax请求_django 接收ajax请求_03

  1. from django.shortcuts import render  

  2. from django.http.response import HttpResponse  

  3. # Create your views here.  

  4. from django.shortcuts import render_to_response  

  5. #导入render_to_response  

  6. from django.shortcuts import render_to_response  

  7. #导入包装的csrf请求,对跨站攻击脚本做处理  

  8. from django.views.decorators.csrf import csrf_exempt  

  9.   

  10. import json  

  11.   

  12. def tt(request):  

  13.     return  render_to_response('em/add.html')  

  14.   

  15.   

  16. names=list();  

  17. names.append("zhangsa")  

  18. names.append("aa")  

  19. names.append("b")  

  20. names.append("c")  

  21.  

  22.  

  23. @csrf_exempt  

  24. def ccc(request):  

  25.   

  26.     name=request.POST.get("name",None)  

  27.     rtxt="";  

  28.     if name is not None:  

  29.         b=name in names  

  30.         if b:  

  31.             #print("名字已经存在!",name)  

  32.             rtxt="名字已经存在!"  

  33.         else:  

  34.             print("名字不存在!")  

  35.             rtxt="名字不存在!"  

  36.     #print("获取的名字是:NU ",name)  

  37.   

  38.     return  HttpResponse(json.dumps({"msg":rtxt}))  




urls里面的代码: 

Python代码  django 接收ajax请求_django 接收ajax请求_03

  1. #ajax校验  

  2.  url(r'^ccc/$',ccc),  




注意里面用到了json.dumps函数来生成json对象,注意词典的形式,在测试之前,最后,先访问一下看看,json数据是否能拿到. 


django 接收ajax请求_django 接收ajax请求_06 





ajax验证没有问题之后,我们就可以在前端进行了,测试效果就是散仙开头所截图,本文的重点在于验证ajax的功能调用,所以并没有直接从数据库里面获取数据进行验证,而是使用了list集合,进行了数据的模拟,如果想做的更完美一点,可以把数据库部分实现,这样就与真实中的网站验证场景就一样了。