【发布时间】:2026-02-14 03:45:01
【问题描述】:
我有一个 html 表单,我使用 Jquery 通过 Php 进行验证。成功将数据插入数据库后,它会在html 页面中显示成功消息并重定向到不同的页面。好吧,它工作正常,但如果出现错误,它也会重定向到不同的页面。
我想要什么:
如果有错误,它应该留在这个页面上。如果没有错误,那么它应该重定向到不同的页面。我怎样才能用 jquery 做到这一点?
<center><img id="loading-image" src="images/loading-image.gif" style="display:none; margin-bottom:10px !important;"/></center>
<div id="result"></div>
$('body').on('click', '#request_tutor', function (e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$("#loading-image").show();
$.ajax({
url: 'request_tutor_process.php',
type: 'POST',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
$("#loading-image").hide(); //hide loading
$("#result").html(data);
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
window.location.href = "login/index.php";
}, 2000);
},
complete: function () {
$("#loading-image").hide(); //hide loading here
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
PHP页面:
$err = array();
// required eata validation checking...
if(isset($name) && isset($tutoring_location) && isset($pcode) && isset($mphone) && isset($email) && isset($tutor_level)){
if(empty($name) && empty($tutoring_location) && empty($pcode) && empty($mphone) && empty($email) && empty($tutor_level)){
$err[] = "Please fill up required field which is indicated by *";
}else{
if(empty($name))
$err[] = "Your name required";
elseif(strlen($name) > 30)
$err[] = "Your name is too long";
if(empty($tutoring_location))
$err[] = "Write your tutoring location";
elseif(strlen($tutoring_location) > 255)
$err[] = "Tutoring location address is too long";
if(empty($pcode))
$err[] = "Postal code required";
elseif(strlen($pcode) > 6)
$err[] = "Invalid postal code";
elseif(!is_numeric($pcode))
$err[] = "Invalid postal code";
if(empty($mphone))
$err[] = "Mobile phone number required";
elseif(strlen($mphone) > 8)
$err[] = "Invalid mobile phone number";
elseif(!is_numeric($mphone))
$err[] = "Invalid mobile phone number";
if(empty($email))
$err[] = "Your email address required.";
elseif(@!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
$err[] = "Invalid email address";
elseif($num_email == 1)
$err[] = "Email address <strong>$email</strong> is already exits, please choose another";
if(empty($tutor_level))
$err[] = "Select your tutor level";
}
if(!empty($err)){
echo "<div class='error'>";
foreach($err as $er){
echo "$er. <br/>";
}
echo "</div>";
}else{
ecoh "success";
}
}
【问题讨论】:
-
您如何使用 jQuery 验证 PHP? PHP 是服务器端,jQuery 是客户端。他们不能直接互动。你真的确定要在整个身体上设置点击事件吗?你的 PHP 代码是什么样的?
-
@Zarathuztra 按下提交按钮后,它使用 jquery on click 方法调用 php 页面。将数据插入到 db php 后,将成功消息返回给 jquery,即
$("#result").html(data); -
@John Barca 感谢您编辑我的问题。