推荐学习书目
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 · Apr 20, 2016 · 3071 views
  •   You need to sign in to view this topic
    This topic created in 3756 days ago, the information mentioned may be changed or developed.

    我想通过 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  
       Apr 20, 2016   ❤️ 1
    chrome F12 看请求
    LeoQ
        2
    LeoQ  
       Apr 20, 2016   ❤️ 1
    CSRF
    imkh
        3
    imkh  
    OP
       Apr 20, 2016
    @LeoQ 已经加了处理代码。
    imkh
        4
    imkh  
    OP
       Apr 20, 2016
    @jugelizi 看不到请求。。。
    LeoQ
        5
    LeoQ  
       Apr 20, 2016
    @imkh 哦看到了, 你这个不能直接返回 302 , 要返回一个成功的消息,然后 javascript 得到成功消息的时候跳转。
    imkh
        6
    imkh  
    OP
       Apr 20, 2016
    @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  
       Apr 20, 2016
    $.post('{% url 'user_login' %}',{username:$("#username").val(),password:$("#password").val()},function(data){
    $("#result").html(data);
    });

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

    准备睡觉了,简单建议一下。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5591 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 01:40 · PVG 09:40 · LAX 18:40 · JFK 21:40
    ♥ Do have faith in what you're doing.