我有一个基本的php验证的简单联系表格,这是代码的相关部分:
$err = '';
if(!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err .= "Name : Only letters and white space allowed.\n";
}
if(strlen($name)<3){
$err .= "Name : Please enter your full name.\n";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err .= "Email : Invalid email format.\n";
}
if(strlen($email)<8){
$err .= "Email : Okay, how about using a correct email address?\n";
}
if(strlen($message)<30){
$err .= "Message : Message too short.\n";
}
if($err != ''){
$err = 'There were few errors : \n '.$err;
//THE ALERT BELOW DOESN'T WORKS, gets added into body code, but does not popup
echo '<script type="text/javascript">alert("'.$err.'");</script>';
// While this one works well
//echo '<script type="text/javascript">alert("This alert works. \nThe one above does not.");</script>';
}
else{
//whatever
}
问题是最后一个if条件中的alert()
不起作用,它会添加到正文代码中但不会弹出。如果我使用普通文本而不是$err
变量(就像注释掉的那样) - 这一切都很好。
过去我曾经多次遇到这个问题,我从来不明白为什么会发生这种情况。什么是解决方案,我总是宁愿删除警报并显示响应消息,通常在div或其他东西,但这次我需要知道 - 为什么??
答案 0 :(得分:1)
将新行改为此
$err .= "Name : Please enter your full name.\\n";
答案 1 :(得分:0)
if($err != ''){
$err = 'There were few errors : \n '.$err;
echo '<script type="text/javascript">alert('.$err.');</script>';
}
else{
//whatever
}