isset($ _ POST ['x'])仅在提交按钮名称=“提交”时有效

时间:2014-05-30 05:16:04

标签: php xhtml

我在使用回发时遇到问题,因为我有多个表单而isset仅适用于name="submit"个按钮。

如果我使用name="submit",我的代码会正常工作,但如果我将名称更改为其他内容,isset($_POST['somethingelse'])将始终为false,为什么会发生这种情况?

编辑:

<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

EDIT2:

<?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 } ?>

例如,在这里,按预期工作(我可以保留值)作为名称=&#34;提交&#34;并且if(isset($ _ POST [&#39; submit&#39;]))在按钮提交时为true,但如果我更改名称=&#34;&#34;和if(isset($ _ POST [&#39;&#39;]))然后它将无法工作,因为isset返回false(即使按钮提交)。

1 个答案:

答案 0 :(得分:2)

这是正常的,因为只设置了点击的提交按钮,而不是第二个,如果您点击名称为提交 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>