表单POST擦除该视图


form POST erases the view

如何让我的简单视图的html项目在表单POST后重新出现?

我在下面布置了html控件,然后当用户选择"上传"提交按钮,文件已上传(成功),但全部先前布置的视图元素消失。再次,上传文件的操作正常。只是我显示的html控件在index.php上,当表单上传到浏览器窗口时就会消失为空。

如何在表单的POST之后返回我的简单视图?

THIS index.php:

<body>
<img src="/theWebsite/images/banner2.jpg" /img>
<br />
<input type="button" value="Play" onclick="showAnAlert(){}" />
     // other buttons and text field html elements not shown
<form enctype="multipart/form-data" action="file-upload.php" method="POST">
      Please choose a file: <input name="uploaded" type="file" /><br />
      <input type="submit" value="Upload" />
 </form>
 </body>

这里是文件上传.php

<?php
    $target = "upload/";
    $target = $target . basename( $_FILES['uploaded']['name']) ;
    $uploadingFile = $_FILES['uploaded']['tmp_name'] ;
    if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
    {
        // I thought the problem was this 'echo' but the main view still goes blank after
         // I commented this out here....
        //echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
     }
     else {
            // echo "errmsg"
           }
 ?> 

将表单发布到file-upload.php后,不会将其重定向回HTML所在的index.php。您需要在完成表单处理后调用重定向:

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
    // I thought the problem was this 'echo' but the main view still goes blank after
     // I commented this out here....
    //echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
    // Redirect back....
    header("Location: http://www.example.com/index.php");
    // Always call exit() right after a redirection header to prevent further script execution.
    exit();
 }
 else {
        // echo "errmsg"
 }

您可能还需要在出现错误的情况下重定向。在这种情况下,将header()调用放在最后。

file-upload.php文件需要在上传完成后将用户重定向回您的index.php,或者需要在底部包含原始的index.php文件。

我建议您要么重定向回,要么简单地将file-upload.php文件全部删除,并在index.php文件中处理它。

对于表单的操作,指定$_SERVER['PP_SELF']变量:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

然后一定要在为表单输出html的同一个.php文件中添加处理表单的逻辑。另一种方法是使用header()调用再次重定向到表单:

<form action="process_form.php" method="POST">

然后,在process_form.php中:

header("Location: http://mydomain.com/form_page.html");