【问题标题】:Keep Request when requesting same route with POST and GET?使用 POST 和 GET 请求相同路由时保持请求?
【发布时间】:2019-01-20 12:40:06
【问题描述】:

我正在尝试制作一个经过验证且应显示错误的简单表单。此外,字段的值应该保留。

我正在使用简单的路由代码来确定要显示的页面。 我的问题是表单的值总是在我提交时重置。 我搜索了一下,发现当请​​求更改时,表单值会丢失。

这是一个展示我想要实现的目标的小例子:

$route = $_SERVER['REQUEST_URI'];

switch ($route) {
    case '/kontakt':
        ?>
        <form method="POST" action="/kontakt">
            <input type="text" required name="test">
            <input type="submit">
        </form><?php
        break;
}

提交后输入的值应留在该字段中。

那么如何在路由到同一路由但一次使用 POST 一次使用 GET 时保留请求而不更改表单值以使用 _POST 数组?

【问题讨论】:

标签: php post get routing request


【解决方案1】:

让我们首先获取我们需要使用哪个请求来获取请求参数。

$request =& $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

在这里检查它是否已设置可能是个好主意,如果未设置 - 将其留空。

$name = $request['name'] ?? ''; # PHP 7+
$name = isset($request['name']) ? $request['name'] : ''; # PHP 5.6 >

然后你可以做你的路由

# switch: endswitch; for readability
switch(($route = $_SERVER['REQUEST_URI'])):
    case '/kontack': ?>
        <form method="POST" action="/kontakt">
        <input type='text' value='<?= $name; ?>' name='name' />
        ....
        <?php break;
endswitch;

然后,这将不断地将名称重新插入value 字段。但是,如果您访问一个新页面然后又回来 - 它就会消失。如果您希望它始终保持在任何路线上,您可以使用会话。

session_start();

# We want to use the request name before we use the session in-case the user
# Used a different name to what we previously knew
$name = $request['name'] ?? $_SESSION['name'] ?? ''; # PHP 7
$name = isset($request['name']) ? $request['name'] : isset($_SESSION['name']) ? $_SESSION['name'] : ''; # PHP 5.6 >

# Update what we know
$_SESSION['name'] = $name;

注意:我展示了 PHP 5.6> 和 PHP 7 的示例。您只需要根据您使用的 PHP 版本使用一个。

【讨论】:

    【解决方案2】:

    当您第一次到达路线时,发送一个 HTML-valueAttribute-variable 作为空值。当您在发布后返回路线时,将发布值发送到 HTML-valueAttribute-variable:

    当您第一次到达路线时:

    <?php
        //Value that is sent to the view/page when accessing route without having posted a value
        $testValue=null
    ?>
        <form method="POST" action="/kontakt">
            <input type="text" required name="test"
                <?php
                    if($testValue != null)
                    {
                        echo "value='".$testValue."'";
                    }
                ?>
            >
            <input type="submit">
        </form>
    

    当你发帖后使用路由时:

    <?php
        //Value that was posted is sent to view/page
        $testValue=$POST['test']
    ?>
        <form method="POST" action="/kontakt">
            <input type="text" required name="test"
                <?php
                    if($testValue != null)
                    {
                        echo "value='".$testValue."'";
                    }
                ?>
            >
            <input type="submit">
        </form>
    

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 2021-12-31
      • 2018-05-26
      • 1970-01-01
      • 2011-12-16
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多