我的base.html中有一个弹出式登录表单
<div id="login-box" class="login-popup">
<a href="#" class="close"><img src="http://localhost:8000/static/media/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>
<form method="post" class="signin" action="{% url login_view %}" id="LoginForm">
<div id="ajaxwrapper">
<fieldset class="textbox">
<label class="username">
<span>Username</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<p id="sendwrapper"></p>
<p><button id="submitbutton" type="submit">Sign in</button></p>
<p>
<a class="forgot" href="/accounts/password/reset/">Forgot your password?</a>
</p>
</fieldset>
</div>
</form>
在提交此表单时,在Django视图中调用以下函数:
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
print "%s" % repr(request.POST)
print "%s" % repr(request.GET)
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
print user
if user is not None:
if user.is_active:
login(request, user)
# success
response_dict = 'success'
return render_to_response("tr/login.html", { 'username' : user , 'response_dict' : response_dict })
else:
# disabled account
response_dict = 'The account is disabled'
return render_to_response("tr/login.html", { 'response_dict' : response_dict })
else:
# invalid login
response_dict = 'Username or Password is not correct'
return render_to_response("tr/login.html", { 'response_dict' : response_dict })
else:
print "%s" % repr(form.errors)
现在我想为每次不成功的尝试保持弹出式登录框,并在成功尝试时关闭它。为此我尝试下面的jQuery代码。但我不知道如何处理它。
jQuery(function() {
var form = jQuery("#LoginForm");
form.submit(function(e) {
var a = 1;
jQuery("#submitbutton").attr('disabled', true)
jQuery("#sendwrapper").prepend('<span>Sending message, please wait... </span>')
if(a==1){jQuery("#ajaxwrapper").load(
form.attr('action') + ' #ajaxwrapper',
form.serializeArray(),
function(responseText, responseStatus) {
jQuery("#sendwrapper").html('<span> AAAAAAAAAAAAAAA </span>')
jQuery("#sendbutton").attr('disabled', false)
}
)}
else{jQuery("#ajaxwrapper").load(
form.attr('action') + ' #ajaxwrapper',
form.serializeArray(),
function(responseText, responseStatus) {
jQuery("#sendwrapper").html('<span> AAAAAAAAAAAAAAA </span>')
jQuery("#sendbutton").attr('disabled', false)
}
)};
e.preventDefault();
});
});
请帮助!!
答案 0 :(得分:0)
在您的login_view中,将“success”返回给模板。如果登录成功,则成功= True,否则成功= False。
在模板中,您可以检查成功是否= = True,关闭弹出窗口。
不过,你的变量有点令人困惑。我建议做这样的事情:response_dict['message'] = 'Login successful.'
response_dict['success'] = True
response_dict['user'] = user
return render_to_response("tr/login.html", response_dict)
如果您执行此操作,也无需将用户传递给模板:https://docs.djangoproject.com/en/dev/topics/auth/#authentication-data-in-templates