PHP echo重定向

时间:2015-08-13 12:33:04

标签: php

我希望在提交表单后回复帖子中的内容,然后重定向标题以取消双重提交问题。目前,Output_buffering已启用以允许重定向工作。这里有一些示例代码来说明问题。只需确保在php.ini中启用Output_buffering。

<?php
   if(isset($_POST['submit'])){
   echo "hi";
}

   if (count($_POST) {
    header("Location: ".$_SERVER['REQUEST_URI']);
    exit();
    }
?>

<form action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST" name="edit" >
    <button type="submit" value="submit" name="submit">edit</button>
</form>

2 个答案:

答案 0 :(得分:0)

你应该撤销订单。

提交时:

  1. 处理您的提交表单。
  2. 将所需的输出消息推送到您的会话中。
  3. 重定向到任何/消息页面。
  4. 在消息页面上显示:

    1. 接收消息,推送到会话。
    2. 清理会话记录。
    3. 显示消息。
    4. 它可以是单独的页面,相同的页面,也可以是提交或任何其他页面。

      或者... 的 使用JavaScript和AJAX进行工作:

      <?php
          if(isset($_POST['submit'])) {
              ...
              if (/all is ok/)
                  die(json_encode(array('status' => 'ok', 'message' => 'Hi!')));
              else {
                  die(json_encode(array('status' => 'err', 'message' => 'I\'m failed!')));
              }
          }
      ?>
      
      <form action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST" name="edit" >
          <button type="submit" value="submit" name="submit">edit</button>
      </form>
      <script language="javascript">
        $('form').submit(function() {
            var parameters = ...; // collect parameters from form
            $.getJSON('/url-to-script', parameters)
             .success(function(response) {
                 if (response.message == "ok")
                     alert(response.message);
                 else
                     alert('Can\'t process input:\n' + response.message);
             })
             .error(function(response) {
                 alert('What a terrible failure!');
             });
        });
      </script>
      

      当.success()触发时 - 您可以通过警报/自定义模式消息框向用户显示提供的消息,然后重定向(document.location = '<?php echo ... ?>')或在页面上替换表单,其中包含一些自定义消息和链接/按钮以继续......很多变种。

答案 1 :(得分:0)

标题必须发送之前任何内容(echo提供的内容)。

您可以将邮件存储到session并在下次请求时打印(这将是您的后续重定向)。

实施例

sessions_init.php

<?php 
session_start();

post.php中

<?php
include_once 'sessions_init.php';
// assuming POST succeeded, data is valid, etc
$_SESSION['messages'][] = 'You have been redirected';

header("Location: ".$_SERVER['REQUEST_URI']);
exit();

html模板:

include_once 'sessions_init.php';
// print HTML:
// <html><head>...</head><body>...

foreach($_SESSION['messages'] as $message) {
   print($message);
}

// some other content </body></html>
相关问题