我想创建一个ajax登录,它发送数据并呈现html而不刷新页面。
我在这里遵循了一些已经解答过的解决方案,
但它给我一个400错误。
如何解决错误,并在指定层(.login_div)中显示用户名等登录信息?
你可以帮帮我吗?{% load staticfiles %}
<html>
<head>
<link rel='stylesheet' href='{% static "css/normalize.css" %}' />
<link rel='stylesheet' href='{% static "css/skeleton.css" %}' />
<link rel='stylesheet' href='{% static "css/index.css" %}' />
</head>
<body>
<script src='{% static "js/jquery.js" %}'></script>
<div class="login_div"></div>
<form id="login_form" method="post" action="{% url 'login' %}">
{% csrf_token %}
<div class="field-wrap">
<label>
Email Address
</label>
<input name="username">
</div>
<div class="field-wrap">
<label>
Password
</label>
<input name="password">
</div>
<p class="forgot"><a href="#">Forgot Password?</a></p>
<button class="button button-block"/>Log In</button>
</form>
<script>
$('form').on('submit', function(e) { e.preventDefault()
$.ajax({
type:"POST",
url: '../login/',
data: $('#login_form').serialize(),
success: function(response){
$('.login_div').text(username)
// do something with response
response['result']; // equals 'Success or failed';
response['message'] // equals 'you"re logged in or You messed up';
}
});
});
</script>
</body>
</html>
和views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseBadRequest
import json
def ajax_login(request):
print(request.method)
print(request.POST)
if request.method == 'POST':
username = request.POST.get('username', '').strip()
password = request.POST.get('password', '').strip()
print("U: %r / P: %r" % (username, password))
if username and password:
# Test username/password combination
user = authenticate(username=username, password=password)
# Found a match
if user is not None:
# User is active
if user.is_active:
# Officially log the user in
login(self.request, user)
data = {'success': True}
else:
data = {'success': False, 'error': 'User is not active'}
else:
data = {'success': False, 'error': 'Wrong username and/or password'}
return HttpResponse(json.dumps(data), content_type='application/json')
# Request method is not POST or one of username or password is missing
return HttpResponseBadRequest()
def index(request):
return render(request, "index.html")