Django ajax 无法提交数据

2016-04-20 21:57:17 +08:00
 imkh

我想通过 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)
2483 次点击
所在节点    Python
8 条回复
jugelizi
2016-04-20 22:02:47 +08:00
chrome F12 看请求
LeoQ
2016-04-20 22:21:10 +08:00
CSRF
imkh
2016-04-20 22:34:11 +08:00
@LeoQ 已经加了处理代码。
imkh
2016-04-20 22:34:25 +08:00
@jugelizi 看不到请求。。。
LeoQ
2016-04-20 22:59:05 +08:00
@imkh 哦看到了, 你这个不能直接返回 302 , 要返回一个成功的消息,然后 javascript 得到成功消息的时候跳转。
imkh
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
2016-04-20 23:15:31 +08:00
$.post('{% url 'user_login' %}',{username:$("#username").val(),password:$("#password").val()},function(data){
$("#result").html(data);
});

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

准备睡觉了,简单建议一下。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/272637

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX