首先,我想说明的是,如果您使用的是任何服务器端应用程序,那么在对它执行任何操作之前,应绝对验证服务器脚本上的输入。客户端验证的目的是让用户更容易输入正确的信息,并且如果javascript关闭,可以轻松入侵或无关紧要......这就是说,在客户端,您可以拦截提交事件,检查不同的字段值。如果您有错误,则显示错误消息,否则,您提交表单。例如:
,如果我们有这样的形式:
<form action"myActionscript.php" method="GET" id="#myForm">
// form items here
</form>
,然后这个脚本(请注意,代码未测试)
<script type="text/javascript">
var f = document.getElementById('myForm');
if (f.addEventListener) { // addEventListener doesn't work in ie prior ie9
f.addEventListener('submit', checkForm);
}else{
f.attachEvent('submit', checkForm);
}
function checkForm() {
// Check all input fields logic,
// you could have an errors array and add an error message for each
// error found. Then you would check the length of the error array,
// submit the form is the length is 0 or not submit the form
// and display errors if the length is > 0.
if (errors.length > 0)
{
// iterate through the array, create final error message
// and display it through an alert or by inserting a new
// DOM element with the error message in it.
// [...]
}else{
f.submit();
}
}
</script>
我不得不说,整个事情就好办多了当然,如果你使用了像jQuery这样的JavaScript库,肯定会有更多的交叉平台...)
我想试试这个,但是当我<?php echo $ firstname; ?>在process.php上我什么也没得到。 – philip 2011-04-27 14:21:17
这可能与我使用window.location从dinner.html移动到process.php有关吗? – philip 2011-04-27 14:22:06
也许,如果表单实际上没有发布到process.php中,那么PHP将不会将表单中的信息提供给它。确保表单正确提交(而不是使用Javascript),并且应该解决问题。 – 2011-04-27 14:22:45