如何確定在具有多個提交按鈕的 PHP 表單中點擊了哪個按鈕?

DDD
發布: 2024-11-14 17:34:02
原創
516 人瀏覽過

How do you determine which button was clicked in a PHP form with multiple submit buttons?

How to Determine the Originating Button in a PHP Form Submission

When designing forms with multiple submit buttons, it becomes crucial to identify which button was clicked upon form submission. This section presents a comprehensive guide to assist developers in achieving this functionality.

Identifying the Submit Button

To differentiate between the submit buttons, PHP utilizes the following approach:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['btnDelete'])) {
        // btnDelete was clicked
    } else {
        // Default to the first submit button (btnSubmit)
    }
}
登入後複製

Consider Default Submit Button

It's essential to acknowledge that the first submit button appearing in the form HTML is considered the default submitter. This principle applies to both single and multi-button forms.

Example: Multi-Button Form

Assuming the following form markup:

<input type="submit" name="btnSubmit1" value="1">
<input type="submit" name="btnSubmit2" value="2">
<input type="submit" name="btnSubmit3" value="3">
登入後複製

PHP code would determine the clicked button as follows:

if (isset($_POST['btnSubmit3'])) {
    // btnSubmit3 was clicked
} elseif (isset($_POST['btnSubmit2'])) {
    // btnSubmit2 was clicked
} else {
    // Default to btnSubmit1 (first submit button)
}
登入後複製

GET Method Considerations

For forms using the GET method, employing $_SERVER['REQUEST_METHOD'] === 'GET' is unreliable. Instead, consider adding a hidden input named 'submitted' and setting its value to 1. This allows for submission detection via isset($_GET['submitted']).

Browser Compatibility

This approach enjoys excellent browser compatibility, extending support to browsers from the early 2000s and beyond. Its logical structure is easily adaptable to other languages.

以上是如何確定在具有多個提交按鈕的 PHP 表單中點擊了哪個按鈕?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板