我正在尝试使用 PHP 验证表单中的字段,但我需要类似于 e.preventDefault() 的东西来在验证出现错误时停止页面刷新/加载。我不太熟悉 JavaScript/jQuery,所以我更愿意用 PHP 处理所有 POST 数据(如果可能)。我试图在提交时运行 checkForm() 函数,但我意识到它总是返回 true,因为它在数据发布之前运行。我还考虑过创建一个 JS 函数来调用 e.preventDefault(),但我认为我唯一的选择是 (#form).submit() 函数,我想避免在 JS/jQuery 中检索和发布数据,因为有些元素是 DOM 元素,我不确定如何在 JS/jQuery 中访问它们。
为了让您了解我正在使用的 DOM 元素,这里有一个动态创建行的 jsfiddle:
https://jsfiddle.net/hnj6ed1y/52/
可能有多行并且字段具有相似的名称(即:textfield1、textfield2 等)。
有什么想法吗?预先感谢您的所有帮助!
<?php
// setting initial variables here
?>
<script>
var isDateTimeValid = true;
function checkDates(val) {
if (val == false) {
isDateTimeValid = false;
}
else {
isDateTimeValid = true;
}
}
function checkForm () {
if (isDateTimeValid == true) {
return true;
}
else {
alert("Please check date/times");
return false;
}
}
</script>
<?php
if(isset($_POST['next'])){
// Validating POST data here
$dateValid = convertOORDateTime($date1, $time1, $date2, $time2);
if ($dateValid < 1) {
echo "<script> checkDates(false); </script>";
$errors[] = 'Please make sure your dates are correct';
}
else {
echo "<script> checkDates(true); </script>";
}
}
$err_msg = '';
if(!empty($errors)){
// want to stop page refresh/load here
$err_msg = '<p class="error">'.implode('<br />', $errors).'</p>';
}
?>
<!DOCTYPE html>
<form name="form1" id="form1" method="post" action="<?php print $thispage;?>" onsubmit="return checkForm()">
<?php echo $err_msg; ?>
</form>
最佳答案
当您的 checkForm 无法阻止表单提交时,这很奇怪。您的 JS 代码可能会抛出错误,然后代码继续运行。
简单的方法是将提交按钮更改为普通按钮。当您单击普通按钮时,表单不会自动提交。验证通过后,您可以通过 jquery 手动提交表单。
$('#button-id').click(function(){
var valid = true;
// perform the validation here, for example
if($('something').val() == "") {
valid = false;
// notice user the error
}
// Continue to validate
// Finally, check the valid
if(valid) {
('#form-id').submit();
}
});
在验证部分,你可能会使用jQuery验证,然后你可以这样做
var form = $( "#myform" );
form.validate();
$( "button" ).click(function() {
if(form.valid()) {
form.submit();
}
});
关于javascript - 提交后PHP防止页面刷新/加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032923/