doushouhe7072 2015-08-13 12:33
浏览 41
已采纳

PHP echo重定向

I want to echo something in a post after submitting a form, then redirecting the header to cancel the double submit problem. Currently, Output_buffering turned on to allow the redirect to work. here some example code that illustrates the problem. Just make sure Output_buffering is on in php.ini.

<?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条回答 默认 最新

  • douyun8885 2015-08-13 12:50
    关注

    You should reverse the order.

    On submit:

    1. Process yours submit form.
    2. Push desired output message into yours session.
    3. Redirect to whatever/message page.

    On message page show:

    1. Retrive message, pushed to session.
    2. Cleanup session record.
    3. Display message.

    It's can be separate page, same page, as with submit for, or any other page.

    Or... Do the work with JavaScript and 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:
    ' + response.message);
           })
           .error(function(response) {
               alert('What a terrible failure!');
           });
      });
    </script>
    

    When .success() fired - you can show supplied message to user via alert/custom modal message box an then make redirect (document.location = '<?php echo ... ?>') or replace form on page with some custom message and link/button to proceed... Lots of variants.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?