我正在通過Ajax將一些數據發送到處理註冊的PHP腳本。我試圖從服務器得到一個響應,無論輸入是否有效(實時驗證)。我希望每個輸入都有自己的響應,這意味着如果第一個輸入仍然無效,並且某人在第二個輸入字段中輸入了無效的內容,那麼第一個響應將保持不變,並且它會發送第二個響應。PHP和Ajax輸入驗證中的If/else語句
現在發生的情況是:第一個輸入無效,我看到響應,但是當我進入下一個輸入字段並在該字段中放置了一些無效字符時,第一個響應停留在那裏(我已經用控制檯的.log在Chrome)
UPDATE:來舉個例子,我看到這樣的:not a valid username!
,然後我把一些無效的電子郵件地址,在未來的領域,我仍然看到not a valid username!
。
這是我的PHP代碼:
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['email2']) && isset($_POST['password'])
&& isset($_POST['firstname']) && isset($_POST['surname']) && isset($_POST['gender']) && isset($_POST['day'])
&& isset($_POST['month']) && isset($_POST['year'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$gender = $_POST['gender'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
if(!preg_match("/^[a-z](?=[\w.]{3,19}$)\w*\.?\w*$/i",$username)){
echo "not a valid username.";
}
else if(filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "OK!";
}
else if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
echo "not a valid email address";
}
else if(strcmp($email,$email2) != 0){
echo "emails are different.";
}
else if(strcmp($email,$email2) == 0){
echo "OK!";
}
else if(!preg_match("[a-zA-Z]*",$firstname)){
echo "Not a valid firstname.";
}
else if(preg_match("[a-zA-Z]*",$firstname)){
echo "OK!";
}
else if(!preg_match("[a-zA-Z]*",$surname)){
echo "not a valid surname.";
}
else if(preg_match("[a-zA-Z]*",$surname)){
echo "OK!";
}
}
,這是JQuery的Ajax代碼:
function handlePost() {
var username = $('#username').val();
var email = $('#email').val();
var email2 = $('#email2').val();
var password = $('#password').val();
var firstname = $('#firstname').val();
var surname = $('#surname').val();
var gender = $('#gender').val();
var day = $('#day').val();
var month = convertMonth($('#month').val())
var year = $('#year').val();
$.ajax({
type: "POST",
url: "handleRegister.php",
data: "username="+username+"&email="+email+"&email2="+email2+"&password="+password+"&firstname="
+firstname+"&surname="+surname+"&gender="+gender+"&day="+day+"&month="+month+"&year="+year,
success: function(resp){
// we have the response
//alert("Server said:\n '" + resp + "'");
console.log("Server said:\n '" + resp + "'")
},
error: function(e){
//alert('Error: ' + e);
console.log("Server said:\n '" + e + "'")
}
});
}
我想這是我使用的if/else來這裏的路上。此外,在這種情況下,我對如何/何時使用isset($ _ POST ['submit'])有些困惑?
在此先感謝。
OK!從未實際印刷。當改變1場時,所有的錯誤出現?我怎樣才能展示我想要的?使用數組索引? – Loolooii 2012-03-01 19:34:42
好吧,我明白了:) – Loolooii 2012-03-01 19:38:27