我想通过 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>
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'),
]
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)
1
jugelizi 2016-04-20 22:02:47 +08:00 1
chrome F12 看请求
|
2
LeoQ 2016-04-20 22:21:10 +08:00 1
CSRF
|
6
imkh OP @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> ``` |
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); }); 我记得数据键值对不需要加双引号 |
8
loading 2016-04-20 23:20:47 +08:00 via Android 1
你在 django 的代码上加入一些 print ,好自己知道提交成功没,到哪一步了。
准备睡觉了,简单建议一下。 |