您正在寻找的就是 AJAX,它没有什么难的,尤其是 jQuery!将数据发送到 PHP 进行验证的问题在于,它会立即否定您对“速度”的要求——当 Javascript 向服务器发出请求以查看是否一切正常时,表单需要挂起。出于这个原因,通常的做法是在 服务器端和客户端进行验证。请注意,我说的是两者,因为您应该始终验证服务器上的数据。
考虑到这一点,让我们开始吧!我将展示如何在不使用验证插件的情况下验证表单 - 对于更大的项目,您可能需要考虑它,但没有它也很容易:
<form id='myform' action='whatever.php' method='POST'>
First Name: <input type='text' name='first_name' class='required'><br>
Last Name: <input type='text' name='last_name'><br>
Email: <input type='text' name='email' class='required'><br>
Zip: <input type='text' name='zip'><br>
</form>
如您所见,我们有名字和电子邮件以及所需的类别,所以我们可以这样做:
$(function() { // wait for the document to be loaded
$('#myform').submit(function() {
var valid = true; // assume everything is okay
// loop through each required field in this form
$('input.required', this).each(function() {
// if the field is empty, mark valid as false
// and add an error class
if($.trim($(this).val()) == '') {
valid = false;
$(this).addClass('error_input');
}
});
// additional validation for email, zip, perhaps
return valid; // if valid is true, continue form submission
});
});
验证插件让这一切变得更整洁、更干净,但如果您只需要快速填写表单,上述方法没有任何问题。这确实很糟糕,因为您必须在两个地方设置验证规则,但除了在服务器上执行 Javascript 或调用服务器获取数据之外,如果您想快速告诉用户有问题,别无选择。
希望这会有所帮助。
编辑:看来我误解了你的问题。如果您想将表单数据传递给 PHP 脚本,让它验证值,并在不加载的情况下将成功或错误返回到页面,您可以执行以下操作:
$('#myform').submit(function() {
// allow submit if we've validated this already
if($(this).data('done')) return true;
var data = $(this).serialize(); // serialize the form data
// you could get the two variables below from the actual form (DRY)
// with $(this).attr('action'); and $(this).attr('method'); but I am
// not sure if that is what you want...
var action = 'validate.php'; // what script will process this
var method = 'POST'; // type of request to make
$.ajax({
type: method,
url: action,
data: data,
dataType: 'json',
success: function(d) {
if(d.code == 'success') {
// everything went alright, submit
$(this).data('done', true).submit();
} else {
alert('something is wrong!');
}
}
});
return false; // don't submit until we hear back from server
});
然后您的 PHP 脚本所要做的就是返回类似这样的内容,使用 json_encode 来指示一切是否正常:
// verify everything...
// data will be in $_POST just like a normal request
if($everythingOK) {
$code = 'success';
} else {
$code = 'error';
}
print json_encode(array('code' => $code));
exit;
我还没有测试过上面的 Javascript,但我很确定它应该是正确的。我希望这有所帮助。 :)