Tôi đang cố gửi biểu mẫu đăng nhập bằng ajax. Tôi bối rối như thế nào tôi phải xử lý các trường hợp ngoại lệ/phản ứng thành công. Tôi nhận được 200 OK từ máy chủ và biểu mẫu trả về lỗi bằng trường mật khẩu/tên người dùng. Làm thế nào tôi có thể nhận được thông báo lỗi để hiển thị hoặc chuyển hướng người dùng đến trang thích hợp tùy thuộc vào phản hồi của máy chủ?Biểu mẫu đăng nhập Django Ajax
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 });
XEM: CẬP NHẬT
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))
MẪU:
7 <tt id="login_error"></tt>
8 <form id="login_form" action="" method="post">
9
10 {{ login_form }}
11 <input type="submit" value="login"/>
12 <input type="hidden" id="request_path" name="next" value="/"/>
13 </form>
14 <p>{{ request.get_full_path }}</p>
15 <tt id='msg'></tt>
Cần lưu ý rằng bạn cần đảm bảo rằng bạn đang xử lý mã thông báo csrf đúng cách hoặc bạn sẽ gặp sự cố với biểu mẫu ajax - https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/#ajax –
Cảm ơn Aidan! Nó đã làm việc. Bây giờ điều duy nhất tôi cần phải tìm ra là làm thế nào để phân tích giá trị 'tiếp theo' từ phản hồi để tôi có thể chuyển hướng trang đúng cách. :) – user1462141
Nó không cần phân tích cú pháp, tôi mong đợi nó là một chuỗi (Tôi không biết mà không nhìn thấy nó được thiết lập như thế nào).Tôi đoán là không có thuộc tính 'tiếp theo' trong dữ liệu POST hoặc GET để giá trị mặc định '/' đang được sử dụng. Bạn sẽ cần phải tìm hiểu cách nó được thiết lập. Xem tài liệu tại đây để biết thêm thông tin về yêu cầu.REQUEST từ điển - https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpRequest.REQUEST –