使用goto处理输入

时间:2013-09-30 13:18:09

标签: php

第一个例子是:

  1. HTTP GET请求加载页面。
  2. HTTP POST请求提交表单。
  3. 表格的数据存储在会话中。
  4. HTTP GET请求加载页面。
  5. 第二个例子是goto使用" reflow"缓冲区,避免额外的HTTP请求。

    1. HTTP GET请求加载页面。
    2. HTTPPOST请求提交表单。
    3. 冲洗缓冲液&显示内容。
    4. 此外,最后一个示例不使用会话。

      301

      <!DOCTYPE html>
      <html>
      <head>
          <!-- ow noez! -->
      </head>
      <body>  
          <?php
          // A very common scenario in user-flow handling is redirecting user to the page itself after submitting form, e.g.
      
          if ($_SERVER['REQUEST_METHOD'] === 'POST') {
              if (isset($_POST['a'])) {
                  // Suppose there was an error & I've populated the error in $_SESSION.
                  // Now I would redirect user back to the form. This is because there
                  // is markup in the upper template hierarchy layer, e.g. "<!-- ow noez! -->"
      
                  header('Location: ' . $_SERVER['REQUEST_URI']);
      
                  exit;
              }
          }
          ?>
      
          <form action="" method="post">
              <?php if (isset($time)):?>
              <pre>This value is from the past: <?=$time?></pre>
              <?php endif;?>
              <pre>Next time: <?php $time = time(); echo $time;?></pre>
      
              <input type="submit" name="a" value="back in time!">
          </form>
      </body>
      </html>
      

      转到

      <?php
      goback:
      
      ob_start();
      ?>
      <!DOCTYPE html>
      <html>
      <head>
          <!-- ow noez! -->
      </head>
      <body>  
          <form action="" method="post">
              <?php if (isset($time)):?>
              <pre>This value is from the past: <?=$time?></pre>
              <?php endif;?>
              <pre>Next time: <?php $time = time(); echo $time;?></pre>
      
              <input type="submit" name="a" value="back in time!">
          </form>
      
          <?php
          // A very common scenario in user-flow handling is redirecting user to the page itself after submitting form, e.g.
      
          if ($_SERVER['REQUEST_METHOD'] === 'POST') {
              if (isset($_POST['a'])) {
                  ob_clean();
      
                  $_POST = [];
                  $_SERVER['REQUEST_METHOD'] = 'GET';
      
                  goto goback;
              }
          }
          ?>
      </body>
      </html>
      

      goto方案是否不优于 301

1 个答案:

答案 0 :(得分:8)

xkcd
&GT; xkcd

您是否考虑过使用AJAX?那你的流程是:

  • HTTP GET获取网页
  • HTTP POST通过AJAX提交数据
  • 完成! (可选)使用JavaScript更新当前视图。

或者,您可以保留当前代码,只需将整个if($_SERVER['REQUEST_METHOD'] === "POST")部分移到goto标签所在的位置即可。换句话说,重组程序的流程;)