2014-01-09 15 views
0

我正在尋找JavaScript和jQuery專家來設置正確的路徑。我有以下代碼,我注意到在函數完成之前,代碼通過focus()並返回false;並且一旦函數返回false,有人會告訴我寫這段代碼的正確方法嗎?謝謝!JavaScript的最佳代碼實踐if-then-else

// validate passwords 
if(!VerifyPassword($("#CurrentPassword").val())) { 
    $("#CurrentPassword").focus(); 
    return false; 
} 
if($("#NewPassword").val() != "") { 
    if(!ValidatePassword($("#NewPassword").val())) { 
     $("#NewPassword").focus(); 
     return false; 
    } 
    if($("#NewPassword").val() != $("#RetypePassword").val()) { 
     alert("The new password is not the same as the retyped password"); 
     return false; 
    } 
} 

function ValidatePassword(password) { 

    if(password.length < 6) { 
     alert("Password must contain at least six characters!"); 
     return false; 
    } 

    re = /[0-9]/; 
    if(!re.test(password)) { 
     alert("Password must contain at least one number (0-9)!"); 
     return false; 
    } 

    re = /[a-z]/; 
    if(!re.test(password)) { 
     alert("Password must contain at least one lowercase letter (a-z)!"); 
     return false; 
    } 

    re = /[A-Z]/; 
    if(!re.test(password)) { 
     alert("Password must contain at least one uppercase letter (A-Z)!"); 
     return false; 
    } 

    return true; 
} 

function VerifyPassword(password) { 

    urlString = "../sql/db_verify_password.php?Password=" + password; 

    /* send calendar updated information and return status message */ 
    $.ajax({ 
     type: "GET", 
     url: urlString, 
     dataType: "xml", 
     success: function(xml) { 
      $(xml).find('Results').each(function() { 
       var status = $(this).find('Status').text(); 

       if(status != "OK") { 
        alert(status); 
        return false; 
       } 
      }); 
     } 
    }); 
} 
+4

你在期待,什麼是實際發生的?目前尚不清楚你的問題是什麼。 –

+1

'通過焦點()'是什麼意思? – n8wrl

+0

.focus()用於將函數綁定到焦點事件。根據你的代碼,它看起來並不像你想要做的那樣,你是否試圖設置焦點? –

回答

0

讓我們來看看代碼中會發生什麼!

你第一個電話

VerifyPassword($("#CurrentPassword").val()) 

導致

$.ajax({ 
    //content omitted 
}); 

現在,在阿賈克斯第一a代表異步。這意味着會提出一些其他資源的請求,但您不會等到請求完成(如果您等待,您可以將其稱爲同步)。
相反,您的代碼執行繼續,將焦點設置爲輸入並返回false。 最後,當請求完成並返回時,將執行您在success:中指定的功能!

認識到這一點,你想改變success:指定的函數內的重點:

+0

您引發了一個想法。我添加了「async:false」參數給我的ajax,並解決了它。 – Ernest

+0

@Ernest請記住,這將**在請求的整個時間內阻止ui-thread **。直到請求結束,用戶將無法與該頁面進行交互。這可能非常令人不安! (這就是爲什麼我沒有在我的答案中提到這種方式) –

+0

我明白。由於這是頁面上的單一表單,因此他們當時不會與其他任何內容進行交互。謝謝你的幫助。我沒有使用過多的StackOverflow,我檢查你的答案是否接受了它? – Ernest