AJAX username validation in Django

2019-05-27 10:23发布

问题:

I want to create asynchronous username validation, where upon change of the value of the username input, the database is accessed to see if that username is valid for use. So far I have this code, which doesn't seem to work. Please help me in finding out where things went wrong. Thanks!

My HTML:

<div>Username</div>
<input type="text" name="id" id="id">
<div id="idval"></div>

My Script:

<script>
function CheckId() {
$.get('/signup/', {username: $(this).val()},
    function(data){
        if(data == "True"){
            $('#idval').html("You may use this ID");
        } else {
            $('#idval').html("Unavailable");
        }
});
}
function onChange(){
 $("#id").change( function() {CheckId()});
}
$(document).ready(onChange);
</script>       

My View:

def signup(request):
    if request.method == "GET":
        p = request.GET.copy()
        if p.has_key('username'):         
            name = p['username']
            if User.objects.filter(username__iexact=name):
                return HttpResponse(False)
            else:
                return HttpResponse(True)

回答1:

in CheckId() $(this).val() isn't going to work. You need $('#id').val()

See this discussion of how the this keyword works