AJAX的回调(成功?)功能

时间:2011-12-06 19:03:58

标签: javascript ajax django callback

当用户在注册页面中输入信息并点击“提交”时,系统会调用usernameCheck()。理论上,它应该向服务器发送一个AJAX请求,该服务器检查用户名是否被占用。如果是,则提醒用户并且不会发生任何其他情况。否则,它会检查密码是否有效。在上一个问题中,我被告知我需要一个回调函数来阻止表单在AJAX异步返回之前提交。相反,我将表单提交放在AJAX请求的success:部分中,因此只有在用户名是唯一且密码有效的情况下才会调用它。

但是,它似乎没有进入密码检查阶段,或显示任何警报......

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").val()}, 
      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
        } else {
            if (passwordCheck()){
                $('#signup_form').submit();
            }
        }
        },
    headers: ajaxHeaders //settings for ajax request
    });

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

function passwordCheck(){
    var pattern =  /[a-z,A-Z,0-9,$,#,@,!,&,%,+,_,-,?]{10,}/  //regexp for valid charachers
    var text = document.getElementById('password').value;
    var msg = document.getElementById('passAlert');
    if(text.length < 10){
        msg.innerHTML = "Passwords need to be at least 10 characters long :(";
        return false;
    } else if (!text.match(pattern)){
        msg.innerHTML = "You have entered an invalid digit (sorry)";
        return false;
    } else if (unacceptable(text)){
        msg.innerHTML = "You can be more creative than that...";
        return false;
    } else if(text != document.getElementById('pass_repeat').value){
        msg.innerHTML = "Your passwords do not match.";
        return false;
    }
    return true;
}

function unacceptable(pwd){ //joins the array, if it matches any one of them 
                                                        //(g means at any point, i means case insensitive) password rejected
    var re = new RegExp(unforgivable.join("|"),"gi");
    return (pwd.toString().match(re) != null);
}

Django注册视图:

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 :(得分:1)

您提到完全合格的域名;

http://omnicloud.me/signup

向我建议您从域中调用服务器,该域与您加载页面的位置不同,并且您正在遇到跨域名浏览器限制。跨域是可能的,但需要更多设置 - 首先尝试使用与加载页面相同的domian工作,

即使用

   /signup

在同一台服务器上,而不是使用http://omni....部分。