且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP如何确定用户是否按下Enter键或Submit按钮?

更新时间:2023-12-03 10:09:04

只要您正确构造HTML,就可以确定使用了哪个按钮

You can identify which button was used provided you structure your HTML correctly

<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Preview">
<input type="submit" name="action" value="Post">

$_POST数组(或$_GET/$_REQUEST)将包含键操作"和已执行按钮的值(无论是否单击).

The $_POST array (or $_GET/$_REQUEST) will contain the key "action" with the value of the enacted button (whether clicked or not).

现在,单击"明确是一种客户端行为-如果您想区分单击和按键,则需要在表单中添加一些脚本以帮助确定.

Now, "clicking" is explicitly a client-side behavior - if you want to differentiate between a click and a keypress, you'll need to add some scripting to your form to aid in that determination.

或者,您可以偷偷摸摸"并使用隐藏的提交,该提交应正确标识要提交的按键,但这可能会对可访问性产生重大影响.

Alternatively, you can be "sneaky" and use a hidden submit that should correctly identify a key-pressed for submission, but this probably has some significant impact on accessibility.

<?php

if ( 'POST' == $_SERVER['REQUEST_METHOD'] )
{
    echo '<pre>';
    print_r( $_POST );
    echo '</pre>';
}

?>
<form method="post">

    <input type="text" name="test" value="Hello World">

    <input type="submit" name="action" value="None" style="display: none">
    <input type="submit" name="action" value="Edit">
    <input type="submit" name="action" value="Preview">
    <input type="submit" name="action" value="Post">

</form>