PHP如何确定用户是否按下Enter键或Submit按钮? [英] How can PHP determine if the user pressed the Enter key or Submit button?

查看:179
本文介绍了PHP如何确定用户是否按下Enter键或Submit按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是,我有多种提交形式的输入.这些提交输入中的每一个都有不同的值,我希望将其保留为提交.

The problem I have is that I have multiple submit inputs in a single form. Each of these submit inputs has a different value and I would prefer to keep them as submit.

每当用户按下 Enter 时,就好像在按下最上方的提交输入一样,因此这在检查单击哪个输入的代码方面引起了问题.

Whenever the user presses Enter, it is as though the topmost submit input is being pressed, and so it is causing problems for the code checking which input was clicked.

PHP是否可以确定是否单击了输入,还是仅当用户按下 Enter 键时选择的输入?

Is there a way for PHP to determine whether or not the input was clicked, or was just the input that was selected when the user pressed the Enter key?

推荐答案

只要您正确构造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>

这篇关于PHP如何确定用户是否按下Enter键或Submit按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆