django + jQuery AJAX验证用户登陆小实例

新建crsf.js参考至自强学堂:http://www.ziqiangxuetang.com/media/django/csrf.js,把crsf.js文件保存至static文件夹的js目录下

jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});


下一步是引入这个文件至模板

<script src="{% static 'jquery/jquery-2.2.0.min.js' %}"></script>
<script src ="{% static 'js/csrf.js' %}"></script>

test.html:

{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>testajax</title>
</head>
<body>
<input type="text" name="username" id="username"/><label id="msg"></label>
<script src="{% static 'jquery/jquery-2.2.0.min.js' %}"></script>
<script src ="{% static 'js/csrf.js' %}"></script>
<script>
    $(function(){
        $("#username").bind("keyup",function(){
            $.ajax({
                type:"POST",
                url:"{% url 'test_post' %}",
                data:{"username":$("#username").val()},
                dataType:"json",
                success:function(data){
                    $("#msg").html(data.msg)
                }
            })
        })
    })
</script>
</body>
</html>


urls:

urlpatterns = [
    url(r'^test/$',views.test),
    url(r'^test/post$',views.test_post,name='test_post'),
]


模板及urls都设置好了,下一步就去views里写个数据验证了,code跟上:

from django.http import JsonResponse
def test_post(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        check_u = User.objects.filter(username=username)#这里要引入你的User
        if check_u.exists():
            msg = "账户已存在"
        else:
            msg = "账户不存在"
        response = {"msg":msg}
    return JsonResponse(response)

def test(request):
    return render(request,'app/accounts/test.html')

msg可以自己定义。

最后达到的效果是边输入边验证,当输入正确时提示已存在,图如下:  

django + jQuery AJAX验证用户登陆小实例_第1张图片

django + jQuery AJAX验证用户登陆小实例_第2张图片

你可能感兴趣的:(django + jQuery AJAX验证用户登陆小实例)