我想提交一个带有 php 变量的表单以输入到 javascript 中,问题是变量仅在发布后设置,这对于它们回显到 javascript 来说为时已晚。当然,如果我再次提交,变量已经被实现到 JavaScript 中并且它应该按预期工作。但是,我宁愿只提交一次。 有什么方法可以在提交之前验证表单吗?这是我的困境的一个例子:
<?php
if(isset($_POST['submit'])){$name=$_POST['name'];}
?>
<html>
<div id="message"></div>
<form action="home.html" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="conditions-met"
onclick=<?php if($name=="bob"){echo"start();";}?>>
</form>
</html>
<script type="text/javascript">
function start(){
document.getElementById('message').innerHTML = 'hello bob';
return true;
}
</script>
最佳答案
男人对你很刻薄!!
基本上,您应该使用 JavaScript 验证字段。
单击提交按钮后进行检查。成功时继续,失败时显示错误消息。
示例
<form id="myForm" onsubmit="return ValidateFields(this)" name="myForm" accept-charset="UTF-8" enctype="multipart/form-data"" action="myPhpScript.php" method="POST">
// html fields
</form>
<script>
function ValidateFields(formObject)
{
var FieldsValid = true;
//Validate the fields and if one of them is not valid set FieldsValid to false
if(!FieldsValid )
{
//show an error message
return false; // Returing false will prevent the form from submitting
}
return true;// the form will be submitted
}
</script>
为了成为忍者,请阅读以下内容:
http://www.script-tutorials.com/form-validation-with-javascript-and-php/
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/validate-forms-javascript.shtml
关于php - 提交前验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319855/