我创建了一个位于对话框内的登录表单。它按预期工作,没有任何 ajax。问题是我想在关闭对话框之前验证登录表单。现在,如果有人点击提交,对话框就会关闭。成功登录就可以了,但是如果出现错误,用户需要再次单击登录以查看错误以找出问题所在。因此,我试图在关闭对话框之前实现 jquery 来验证数据。
模板
<a id="login_div" onclick="toggleOverlay();" stlye="color:blue; cursor:pointer;">login or register</a>
76 <div class="overlay">
77 <div class="wrap-outer">
78 <div class="wrap">
79 <div class="my-dialog">
80 <a style="color:blue; cursor:pointer;" onclick="toggleOverlay();">Close</a>
81
82 <form id="login_form" name="login_form" action="" method="post">
83
84
85 <h3 id="login_header">Login</h3>
86
87 <label id="login_username">Username:</label>
88 <label id="login_form_username">{{ request.login_form.username }}< /label>
89 <label id="login_password" for="password">Password:</label>
90 <label id="login_form_password">{{ request.login_form.password }} </label>
91
92 {% csrf_token %}
93
94 <input id="login_button" type="submit" name="login_name" value="login" />
95 <input type="hidden" id="request_path" name="next" value="{{ request.path }}"/>
96
97 </form>
jQuery
1 $(window).load(function(){
2 $('#login_form').submit(function(e){
3 var request_url = document.getElementById('#request_path')
4 $.ajax({
5 type:"POST",
6 url: request_url,
7 data:$('#register_form').serialize(),
8 error: function(xhr, ajaxOptions, thrownError){ alert(thrownError); },
9 success: function(data){}
10 });
11 e.preventDefault();
12 });
13 });
看法
13 def process_request(self, request):
14
15 # if the top login form has been posted
16 if request.method == 'POST':
17
18 # validate the form
19 lform = AuthenticationForm(data=request.POST)
20 if lform.is_valid():
21
22 # log the user in
23 django_login(request, lform.get_user())
24 return HttpResponseRedirect(request.REQUEST.get('next', '/'))
25
26
27 # if this is the logout page, then redirect to /
28 # so we don't get logged out just after logging in
29 else:
30 lform
31
32 else:
33 lform = AuthenticationForm(request)
34
35 # attach the form to the request so it can be accessed within the templates
36 request.login_form = lform
TL;DR:我想使用 jquery 验证登录表单,并在成功验证后关闭对话框。