我想提出用ajax登录表单。 我很困惑,我应该如何处理异常/成功响应。 我从服务器得到一个200 OK和形式返回错误的或者由密码/用户名字段。 我怎样才能得到显示或将用户重定向到依赖于服务器的响应相应页面的错误信息?
JQUERY:
56 $(window).load(function(){
57 $('#login_form').submit(function(e){
58 e.preventDefault();
59 var request_url = document.getElementById('next').value
60 $.ajax({
61 type:"POST",
62 url: $(this).attr('action'),
63 data: $('#login_form').serialize(),
64 success: function(response){ $('#msg').text(response);
65 console.log(response);
66 },
67 error: function(xhr, ajaxOptions, thrownError){ alert( $('#login_error').text('Username already taken. Please select another one.')},
68 });
69 });
70 });
VIEW:更新
51 def login(request):
52 if request.method == 'POST':
53 request.session.set_test_cookie()
54 login_form = AuthenticationForm(request, request.POST)
55 if login_form.is_valid():
56 if request.is_ajax:
57 user = django_login(request, login_form.get_user())
58 if user is not None:
59 return HttpResponseRedirect(request.REQUEST.get('next', '/'))
**else:**
61 **return HttpResponseForbidden() # catch invalid ajax and all non ajax**
60 else:
61 login_form = AuthenticationForm(request)
62
63 c = Context({
64 'next': request.REQUEST.get('next'),
65 'login_form': login_form,
66 'request':request,
67 })
68 return render_to_response('login.html', c, context_instance=RequestContext(request))
形成:
7
8
9
10 {{ login_form }}
11
12
13
14
{{ request.get_full_path }}
15