简体   繁体   English

django 中的 ajax 成功 function 不工作

[英]ajax in django success function is not working

I am new in ajax as well as Django.我是 ajax 和 Django 的新手。 I try to put ajax in my code to check that in the signup page if some user is already having one email then that email can't use for new users and disable the button else if the email does not exist then the user can be created. I try to put ajax in my code to check that in the signup page if some user is already having one email then that email can't use for new users and disable the button else if the email does not exist then the user can be created .

ajaxCode ajax代码


$(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 url.py

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

views.py视图.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')

In views.py print(em) is also printing mail that type in field but don't know why is not working.在 views.py print(em)中也打印了在字段中输入但不知道为什么不起作用的邮件。 template模板

{% 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 %}

try this inside succcess function试试这个成功 function

$('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);
    }
   })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM