當用戶將他們的信息輸入到註冊頁面並點擊「提交」時,usernameCheck()
被調用。理論上,它應該向服務器發送一個AJAX請求,該服務器檢查用戶名是否被採用。如果是,那麼用戶會收到警報,沒有其他事情發生。否則,它會檢查密碼是否有效。在之前的問題中,我被告知需要一個回調函數來在AJAX異步返回之前停止提交表單。相反,我將表單提交到AJAX請求的success:
部分,因此只有在用戶名是唯一的且密碼有效時才應該調用。AJAX的回撥(成功?)功能
但是,它似乎並沒有得到過的密碼檢查階段,或顯示任何警報...
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))
打開您的瀏覽器工具(F12)並檢查是否發送了任何內容。 –
嘗試提醒(響應);裏面的成功功能和檢查其值 – mithunsatheesh
@mithunsatheesh呃哦,沒有警報顯示。你看到什麼會導致這不會編譯?我還包括了Django視圖,儘管看起來很簡單,它不應該失敗。 – Chris