此PHP编码正确显示了错误消息。但是,我的问题是,如果注册表格有错误,则弹出框不坚持。例如,如果单击链接,将打开一个弹出框。在那个弹出框中,我包括了一个注册表格。在此注册表格中,所有字段都是强制性的。因此,用户应填写所有字段。如果他没有填写至少一个文本固定的php显示错误消息。
我正确地收到了错误消息。但是,当我提交表格时,整个页面正在刷新。因此,弹出框关闭了。我的问题是 ->如果用户在注册表格中有错误,则弹出框不应关闭。如何做?
php
<?php
$errname = "";
$errmobile = "";
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($_POST["form"] == "values")
{
if(empty($name))
{
$errname = '<span>error</span>';
}
if(empty($mobile))
{
$errmobile = '<span>error</span>';
}
}
?>
html
<p>register <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a></p>
<div id="light" class="white_content">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<input type="hidden" name="form" value="values" />
name : <input name="name" type="text" value="<?php $_POST["name"]; ?>" /> <?php if(isset($errname)) echo $errname; ?> <br />
mobile : <input name="mobile" type="text" value="<?php $_POST["mobile"]; ?>" /> <?php if(isset($errmobile)) echo $errmobile; ?> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
您可以以这种方式使用Ajax进行
验证.php
<?php
$name = $_POST["name"];
$mobile = $_POST["mobile"];
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
?>
您的html
<p>register <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a></p>
<div id="light" class="white_content">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /> <br />
mobile : <input name="mobile" id="mobile" type="text" /> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
ajax.js
在您的 html
中包括此JS文件$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'validation.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#name").val('Name required');
}
if(msg=='error_m')
{
$("#mobile").val('Mobile required');
}
}
});
e.preventDefault();
});
});
您需要在发送到服务器之前使用JavaScript验证表单。然后,如果有错误,则可以return false
。在您的输入中添加:
<input type="submit" value="submit" onSubmit = "return validate();">
然后JavaScript函数:
function validate(){
if(valid == false){
return false;
alert('error');
}
}