我如何知道在PHP表单提交中单击了哪个按钮? [英] How can I tell which button was clicked in a PHP form submit?

查看:264
本文介绍了我如何知道在PHP表单提交中单击了哪个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面上有几个按钮,但是我不确定如何知道单击了哪个按钮. 这是我的两个按钮的标记:

I have several buttons on my page, but I'm not sure how to tell which one was clicked. Here's the markup for my two buttons:

<input type="submit" id="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" value="Delete" />

推荐答案

具有HTML格式,例如:

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

要使用的PHP代码如下:

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

您应该始终假定或默认为第一个提交按钮以HTML源代码的形式出现.实际上,在以下情况下,各种浏览器会可靠地发送带有发布数据的提交按钮的名称/值:

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. 用户实际上使用鼠标或定位设备单击提交"按钮
  2. 或者将焦点放在提交"按钮(在其上具有选项卡)上,然后按下 Enter 键.

存在其他提交表单的方法,在某些情况下,某些浏览器/版本决定不发送任何提交按钮的名称/值.例如,当光标/焦点位于文本字段上时,许多用户通过按 Enter 键提交表单.表单也可以通过JavaScript以及其他一些晦涩的方法提交.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

注意这一点很重要,否则用户提交表单时确实会让他们感到沮丧,但是什么也没有发生"并且他们的数据丢失了,因为您的代码无法检测到表单提交,因为您没有可以预见一个事实,即提交按钮的名称/值可能不会与帖子数据一起发送.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

此外,上述建议也应用于具有单个提交按钮的表单,因为您应该始终假定默认的提交按钮.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

我知道Internet上充斥着大量的表单处理程序教程,并且几乎所有它们都只检查提交按钮的名称和值.但是,他们完全是错误的!

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

这篇关于我如何知道在PHP表单提交中单击了哪个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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