在注册过程中检查重复键(Django,JS,Ajax)

时间:2011-12-06 01:05:36

标签: javascript jquery python ajax django

我有一个名为onsubmit的javascript函数:

function formCheck(){
    return usernameCheck() && passwordCheck();
}

passwordCheck()工作正常并按原样返回,但出于某种原因usernameCheck()遇到问题:

function usernameCheck(){ //returns true if username is free
var ajaxHeaders = {}; //create header object
ajaxHeaders["X-CSRFToken"] = getCookie('csrftoken'); //add csrftoken from cookies for authentication server-side
$.ajax({
    type:'POST',
    url:"http://omnicloud.me/signup", 
  data:{username: $("#username").value}, 
  success:function(response){
    if(response=="true"){
       $('#passAlert').innerHTML("Sorry, that username is already taken") 
       //passalert is where all of the errors (username taken, invalid password) show up
    }
    },
headers: ajaxHeaders //settings for ajax request
});

return !($('#passAlert').value == "Sorry, that username is already taken")
}

在后端:

def signup(request):
if request.method == 'GET':
    return render_to_response('signup.html', context_instance=RequestContext(request))
elif request.is_ajax(): 
#query db for user with username provided via ajax, return if it exists
    try:    
        user = User.objects.get(username=request.POST.get("username")) 
    except User.DoesNotExist:
        return HttpResponse("false",context_instance=RequestContext(request))
    else:
        return HttpResponse("true", context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:2)

Ajax中的A代表异步。您提供的成功函数不会立即执行,它会在浏览器从服务器获得响应后调用,该响应将在之后从usernameCheck()函数返回

您无法使用返回值进行此检查,您必须使用回调。