理想几岁 2017-10-23 21:49:27 5795次浏览 1条回复 0 0 0

各位路过大神,请教一个Ajax提交表单的问题: 大致过程是这样的,我一开始分别用login.html和reg.html页面可以顺利实现登录和注册。可是把登录和注册改成模态框,并用Ajax提交表单内容一直不能成功,数据可以顺利提交到后端,注册信息也能保存到数据库中,但是就是Ajax不能success,并且返回页面后也没有显示登录状态。望各位大神可以帮我解答。我的程序如下: views.py

@csrf_exempt
def do_reg(request):
    try:
        if request.method == 'POST':
            reg_form = RegForm(request.POST)
            if reg_form.is_valid():
                # 注册
                user = MyUser.objects.create(username=reg_form.cleaned_data["username"],
                                    email=reg_form.cleaned_data["email"],
                                    password=make_password(reg_form.cleaned_data["password"]),)
                user.save()

                # 登录
                user.backend = 'django.contrib.auth.backends.ModelBackend' # 指定默认的登录验证方式
                login(request, user)
                return redirect(request.META['HTTP_REFERER'])
            else:
                return render(request, 'failure.html')
        else:
            reg_form = RegForm()
    except Exception as e:
        logger.error(e)
    return redirect(request.META['HTTP_REFERER'], locals())

登录

@csrf_exempt
def do_login(request):
    try:
        if request.method == 'POST':
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                # 登录
                username = login_form.cleaned_data["username"]
                password = login_form.cleaned_data["password"]
                user = authenticate(username=username, password=password)
                if user is not None:
                    user.backend = 'django.contrib.auth.backends.ModelBackend' # 指定默认的登录验证方式
                    login(request, user)
                    return render(request, 'failure.html')
                return redirect(request.META['HTTP_REFERER'])
            else:
                return render(request, 'failure.html')
        else:
            login_form = LoginForm()
    except Exception as e:
        logger.error(e)
    return redirect(request.META['HTTP_REFERER'], locals())

模板

<div id="cd-login"> <!-- log in form -->
	<form class="cd-form" id="login_form" action="{% url 'login' %}">
     {% csrf_token %}
        <p class="fieldset">
			<label class="image-replace cd-email" for="signin-username">Username</label>
			<input class="full-width has-padding has-border" id="signin-username" type="text" placeholder="Username" name="username">
		</p>

		<p class="fieldset">
			<label class="image-replace cd-password" for="signin-password">Password</label>
			<input class="full-width has-padding has-border" id="signin-password" type="text"  placeholder="Password" name="password">
			<a href="#0" class="hide-password">Hide</a>
		</p>

		<p class="fieldset">
			<input class="full-width" type="submit" value="Login" id="login">
		</p>
        <input type="hidden" name="next" value="{{ request.path }}">
	</form>

	<p class="cd-form-bottom-message"><a href="#0">Forgot your password?</a></p>
    
    <div id="cd-signup"> 
		<form class="cd-form" id="signup_form" action="{% url 'reg' %}">
        {% csrf_token %}
		<p class="fieldset">
			<label class="image-replace cd-username" for="signup-username">Username</label>
			<input class="full-width has-padding has-border" id="signup-username" type="text" placeholder="Username" name="username">
		</p>
		<p class="fieldset">
			<label class="image-replace cd-email" for="signup-email">E-mail</label>
			<input class="full-width has-padding has-border" id="signup-email" type="email" placeholder="E-mail" name="email">
		</p>
		<p class="fieldset">
			<label class="image-replace cd-password" for="signup-password">Password</label>
			<input class="full-width has-padding has-border" id="signup-password" type="text"  placeholder="Password" name="password">
			<a href="#0" class="hide-password">Hide</a>
		</p>
		<p class="fieldset">
			<input class="full-width has-padding" type="submit" value="Create account" id="signup">
		</p>
	  </form>
  </div> <!-- cd-signup -->`

JS部分

$(document).ready(function () {
	$.ajaxSetup({
		data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
	});
	$("#login_form").on('submit', function () {
		var username = $('#signin-username').val();
		var password = $('#signin-password').val();

		$.ajax({
			type: "POST",
			url:  $("#login_form").attr('action'),
			data: {"username": username, "password": password},
			dataType: "json",
			success: function (data) {
				if(data > 0){
					alert('操作成功')
				}
				console.log(data);
            }
		});
    });
});

$(document).ready(function () {
	$.ajaxSetup({
		data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
	});
	$("#signup_form").on('submit', function () {
		var username = $('#signup-username').val();
		var password = $('#signup-password').val();
		var email = $('#signup-email').val();

		$.ajax({
			type: "POST",
			url:  $("#signup_form").attr('action'),
			data: {"username": username, "password": password, "email": email},
			dataType: "json",
			success: function (data) {
				console.log(data);
            }

		});
    });
});
您需要登录后才可以回复。登录 | 立即注册