V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
imkh
V2EX  ›  Python

Django ajax 无法提交数据

  •  
  •   imkh · 2016-04-20 21:57:17 +08:00 · 2482 次点击
    这是一个创建于 3140 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我想通过 ajax 提交数据到后台验证用户名和密码,如果出错,就在当前页提示错误。 下面是我的代码,为什么点击登录没有反应?是哪里错了?对 jQuery 不是很懂。

    login.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">
    
        <title>signin</title>
        <script src="{{ STATIC_URL }}jquery/jquery-2.2.3.min.js"></script>
        <!-- Bootstrap core CSS -->
        <link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet">
    
        <!-- TODC Bootstrap core CSS -->
        <link href="{{ STATIC_URL }}bootstrap/css/todc-bootstrap.min.css" rel="stylesheet">
    
        <!-- Custom styles for this template -->
        <link href="{{ STATIC_URL }}css/signin.css" rel="stylesheet">
          <script>
              /*====================django ajax ======*/
    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'));
        }
    });
    /*===============================django ajax end===*/
          </script>
    
      </head>
    
      <body>
    
        <div class="container">
    
          <h2 class="form-signin-heading text-center">sign in</h2>
    
          <div class="card card-signin">
            <img class="img-circle profile-img" src="{{ STATIC_URL }}css/avatar.png" alt="">
            <form class="form-signin">
              <label for="inputEmail" class="sr-only">Username</label>
              <input type="text" id="inputEmail" class="form-control" placeholder="Username" name="username" required autofocus>
              <label for="inputPassword" class="sr-only">Password</label>
              <input type="password" id="inputPassword" class="form-control" placeholder="Password" name="password" required>
                <p class="text-error" id="result"></p>
              <button class="btn btn-lg btn-primary btn-block" type="button" id="signin">Sign in</button>
            </form>
          </div>
    
        </div> <!-- /container -->
    
    <script>
        $(function(){
             $.ajaxSetup({
                    data:{csrfmiddlewaretoken: '{{ csrf_token }}'}
                });
                $("#signin").click(function(){
                    $.post('{% url 'user_login' %}',{"username":$("#username").val(),"password":$("#password").val()},function(data){
                       $("#result").html(data);
                    });
                });
        });
    </script>
    
    
      </body>
    </html>
    
    

    urls.py

    urlpatterns = [
        url(r'^signin/$', 'assets.views.signin', name='signin'),
        url(r'^login/$', 'assets.views.user_login', name='user_login'),
        url(r'^logout/$', 'assets.views.user_logout', name='user_logout'),
    ]
    

    views.py

    from django.http import HttpResponseRedirect
    from django.http import JsonResponse
    def user_login(request):
        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username=username, password=password)
            if user:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect('/index/')
                else:
                    return HttpResponseRedirect('/signin/')
            else:
                response = {'error_info': 'error!'}
                return JsonResponse(response)
    
    jugelizi
        1
    jugelizi  
       2016-04-20 22:02:47 +08:00   ❤️ 1
    chrome F12 看请求
    LeoQ
        2
    LeoQ  
       2016-04-20 22:21:10 +08:00   ❤️ 1
    CSRF
    imkh
        3
    imkh  
    OP
       2016-04-20 22:34:11 +08:00
    @LeoQ 已经加了处理代码。
    imkh
        4
    imkh  
    OP
       2016-04-20 22:34:25 +08:00
    @jugelizi 看不到请求。。。
    LeoQ
        5
    LeoQ  
       2016-04-20 22:59:05 +08:00
    @imkh 哦看到了, 你这个不能直接返回 302 , 要返回一个成功的消息,然后 javascript 得到成功消息的时候跳转。
    imkh
        6
    imkh  
    OP
       2016-04-20 23:08:36 +08:00
    @LeoQ 现在是这段代码没生效,不知道为什么
    ```
    $("#signin").click(function(){
    $.post('{% url 'user_login' %}',{"username":$("#username").val(),"password":$("#password").val()},function(data){
    $("#result").html(data);
    });
    });
    ```

    ```
    <form class="form-signin">
    <input type="text" id="username" class="form-control" placeholder="Username" name="username" required autofocus>
    <input type="password" id="password" class="form-control" placeholder="Password" name="password" required>
    <p class="text-error" id="result"></p>
    <button class="btn btn-lg btn-primary btn-block" type="button" id="signin">Sign in</button>
    </form>
    ```
    jugelizi
        7
    jugelizi  
       2016-04-20 23:15:31 +08:00
    $.post('{% url 'user_login' %}',{username:$("#username").val(),password:$("#password").val()},function(data){
    $("#result").html(data);
    });

    我记得数据键值对不需要加双引号
    loading
        8
    loading  
       2016-04-20 23:20:47 +08:00 via Android   ❤️ 1
    你在 django 的代码上加入一些 print ,好自己知道提交成功没,到哪一步了。

    准备睡觉了,简单建议一下。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1404 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 17:06 · PVG 01:06 · LAX 09:06 · JFK 12:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.