我在使用回发时遇到问题,因为我有不止一种表单,而且 isset
仅适用于 name="submit"
按钮。
如果我使用 name="submit"
我的代码会正常工作,但如果我将名称更改为其他名称,isset($_POST['somethingelse'])
永远都是假的,为什么会这样?
编辑:
<input type="submit" name="submit" value="Submit" onclick ="validate(document.getElementById('form')); return false;" />
if (isset($_POST['submit'])) <-- works as expected
<input type="submit" name="asdf" value="Submit" onclick ="validate(document.getElementById('form')); return false;" />
if (isset($_POST['asdf'])) <-- does not works as expected
编辑2:
<?php
$validated = false;
if (isset($_POST['submit'])) {
// preserve form values by storing the values from $_POST into variables
$test = $_POST['test'];
// validated is now true as submit button only submits if validated (script)
$validated = true;
} else {
// make variables empty as there's no values to preserve
$test = '';
}
if (!$validated) {
?>
<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>Test: <input type="text" name="test" size="20" value="<?php echo $test ?>" /></p>
<p><input type="submit" name="submit" value="Submit" onclick ="validate(); return false;" /></p>
<?php } ?>
例如这里,按预期工作(我可以保留值)作为 name="submit"并且 if (isset($_POST['submit'])) 在按钮提交时为真但如果我更改两个名称=""和 if (isset($_POST[''])) 然后它将不起作用,因为 isset 返回 false(即使按钮提交)。
最佳答案
这是正常的,因为只有点击的提交按钮被设置,而不是第二个,如果你点击名称为 submit 的提交按钮 isset($_POST['submit'])
会给你 true 和 isset($_POST['asdf'])
false,如果你点击 asdf isset($_POST['submit'])
给出 false 和 isset($_POST['asdf'])
true ,我对其进行了测试,它可以正常工作。
测试代码:
<?php
$validated = false;
if (isset($_POST['submit'])) {
// preserve form values by storing the values from $_POST into variables
$test = "submit";
// validated is now true as submit button only submits if validated (script)
$validated = true;
}
else if(isset($_POST['asdf'])){
$test = "asdf";
// validated is now true as submit button only submits if validated (script)
$validated = true;
}
else {
// make variables empty as there's no values to preserve
$test = '';
}
if (!$validated) {
echo $test;
} ?>
<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>Test: <input type="text" name="test" size="20" value="<?php echo $test ?>" /></p>
<p><input type="submit" name="submit" value="Submit" onclick ="validate(); return false;" /></p>
<p><input type="submit" name="asdf" value="Submit" onclick ="validate(document.getElementById('form')); return false;" />
</p>
关于php - isset($_POST ['x' ]) 仅在提交按钮名称为 ="submit"时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23947511/