django成功函数中的ajax不起作用



我是ajax和Django的新手。我试着在我的代码中放入ajax,以在注册页面中检查如果某个用户已经有一封电子邮件,则该电子邮件不能用于新用户,并禁用该按钮,否则如果该电子邮件不存在,则可以创建该用户。

ajaxCode


$(document).on('blur', 'input[name="email"]', function(){
$.ajax({
type:'POST',
url:'/stock/checkemail/',
data:{
email:$("#email").val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
$('input[type="submit"]').attr('disabled', 'true')
},
failure:function(){
$('input[type="submit"]').removeAttr('disabled');
}
})
});

url.py

path('checkemail/',Emailser.as_view()),

视图.py

class Emailser(View):
def post(self, request):
em = request.POST['email']
print(em)
try:
user = User.objects.get(email=em)
return HttpResponse('true')
except:
return HttpResponse('false')

在views.py中,print(em)也在打印在字段中键入但不知道为什么不起作用的邮件。模板

{% extends 'base.html' %}
{% block content %}
{% load static %}
<div>
<h2>Sign Up</h2>
{% if error %}
{{error}}
<br/>
{% endif %}
<form method="post" id="signup" >
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary" >Signup</button>
</form>
</div>
<script src="{% static 'assets/signup.js' %}" ></script>
{% endblock %}

在success函数中尝试此操作

$('input[type="submit"]').disabled = true;
$(document).on('blur', 'input[name="email"]', function(){
$.ajax({
type:'POST',
url:'/stock/checkemail/',
data:{
email:$("#email").val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(response){
response ? $('input[type="submit"]').attr('disabled', 'true') :  $('input[type="submit"]').removeAttr('disabled');
},
failure:function(error){
console.log(error);
}
})
});

最新更新