提交表单后,Textarea 不保留其内容

Textarea doesn't keep its contents after a form submission

我试图在提交表单后在其字段中保留文本区域内容。

每次单击提交按钮时,我都会丢失文本区域的内容,因为文本区域会被清除。

表单和文本区域代码:

<form method="post" action="ProcessText.php" role="form" id="TextEntry">
                    <fieldset style=" height: auto; margin-left: 4%; margin-top: 4%; margin-right: 4%; border: solid 1px black !important; border-radius: 5px; padding: 0 10px 10px 10px; border-bottom: none;">
                        <legend style=" width: auto !important; height: auto !important; border: none; font-size: 17px"><b>Text Entry</b></legend>
                        <div class="form-group" style=" margin-bottom: 3px;margin-top:20px; margin-left: 5%; margin-right: 5%;">
                            <div style="position: absolute; margin-top: 5px"><label for="TextArea" class="label label-primary" >Text Area</label></div><br>
                            <div style="position: relative"><textarea style=" resize: none" id = "TextArea" name="TextArea" class="form-control"
                                                                      rows = "19"
                                                                      cols = "50"
                                                                      style=" width: auto; height: auto; text-align: left; border-right: 1px solid#c0c0c0; " placeholder="Add some text"><?php if(isset($_POST['TextArea'])) { echo htmlentities ($_POST['TextArea']); }?></textarea></div>        
                        </div>
                        <br><button style="float: right; margin-right: 5%" type="submit" class="btn btn-success" name="Submit">Analyse</button>
                    </fieldset>
                </form>

表单和文本区域位于 index.php 页面中,该页面提交到另一个页面(即 ProcessText.php)。提交运行成功,ProcessText.php 页面按预期收到发布的数据。

我在论坛上寻找答案并尝试了很多解决方案,例如将以下代码放在 textarea 标签中:

<?php if(isset($_POST['textarea1'])) { 
         echo htmlentities ($_POST['textarea1']); }?>

我也在 textarea 标签中尝试了这段代码,但没有任何好处:

<?php echo $_POST['TextArea'] ? $_POST['TextArea'] : "" ?>

为了澄清起见,包含文本区域的 index.php 页面代码:

<html>
    <head>
        <title>Text Sorting Form</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link rel="stylesheet" type="text/css" href="css/Styles.css"/>
        <script src="js/jquery-2.1.4.min.js" type="text/javascript"></script>
        <script src="js/bootstrap.min.js" type="text/javascript"></script>
        <style> </style>
    </head>
    <body>


        <div style="width: 100%; overflow: hidden;">

            <div style=" background-color: white; border: 1px solid Grey; 
                 border-radius: 3px; box-shadow: 3px 0px 3px #888888; 
                 width:50%; max-width: 50%; height: 90%; margin-top:3%; margin-left: 
                 3%; margin-right:auto; overflow: hidden; float: left;">
                <form method="post" action="ProcessText.php" role="form" id="TextEntry">
                    <fieldset style=" height: auto; margin-left: 4%; margin-top: 4%; margin-right: 4%; border: solid 1px black !important; border-radius: 5px; padding: 0 10px 10px 10px; border-bottom: none;">
                        <legend style=" width: auto !important; height: auto !important; border: none; font-size: 17px"><b>Text Entry</b></legend>
                        <div class="form-group" style=" margin-bottom: 3px;margin-top:20px; margin-left: 5%; margin-right: 5%;">
                            <div style="position: absolute; margin-top: 5px"><label for="TextArea" class="label label-primary" >Text Area</label></div><br>
                            <div style="position: relative"><textarea style=" resize: none" id = "TextArea" name="TextArea" class="form-control"
                                                                      rows = "19"
                                                                      cols = "50"
                                                                      style=" width: auto; height: auto; text-align: left; border-right: 1px solid#c0c0c0; " placeholder="Add some text"></textarea></div>        
                        </div>
                        <br><button style="float: right; margin-right: 5%" type="submit" class="btn btn-success" name="Submit">Analyse</button>
                    </fieldset>
                </form>
            </div>


            <div style=" background-color: white; border: 1px solid Grey; 
                 border-radius: 3px; box-shadow: 3px 0px 3px #888888; 
                 width:40%; margin-left: 700px; height: 90%; margin-top:3%;">
                <fieldset style=" height:90%; margin-left: 4%; margin-top: 5%; margin-right: 4%; margin-bottom: 10px; border: solid 1px black !important; border-radius: 5px; padding: 0 10px 10px 10px; border-bottom: none;">
                    <legend style=" width: auto !important; height: auto !important; border: none; font-size: 17px"><b>Result</b></legend>
                    <div class="Notes" style=" margin-bottom: 3px;margin-top:40px; margin-left: 5%; margin-right: 5%; height: 75%; width: auto">

                        <?php
                        session_start();

                        // Display Custom Field Value
                        echo '<pre>';
                        echo nl2br("The Submitted Paragraph:\n".$_SESSION['Text']."\n\n");
                        echo nl2br ("Number of Words: " . $_SESSION['number']."\n\n");
                        echo nl2br("Word Frequency in Descending Order:\n");
                        print_r($_SESSION['results']);
                        echo '</pre>';
                        session_unset();
                        session_destroy();
                        ?>

                    </div>
                </fieldset>

            </div>

        </div>     
    </body>
</html>

ProcessText.php页面代码:

<html>
    <head>
        <title>Text Sorting Form</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link rel="stylesheet" type="text/css" href="css/Styles.css"/>
        <script src="js/jquery-2.1.4.min.js" type="text/javascript"></script>
        <script src="js/bootstrap.min.js" type="text/javascript"></script>
        <style>

        </style>
    </head>
    <body>
        <?php session_start(); ?>

        <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST") {


            $text = $_POST['TextArea'];
            $wordcount = word_count ($text);
            $words = utf8_str_word_count($text, 1);
            $frequency = array_count_values($words);
            arsort($frequency);
            $_SESSION['results'] = $frequency;
            $_SESSION['number'] = $wordcount;
            $_SESSION['Text'] = $text;
            header("location: index.php");
            exit();

        };

        function utf8_str_word_count($string, $format = 0, $charlist = null) {
            $result = array();


            if (preg_match_all('~[\p{L}\p{Mn}\p{Pd}\'\x{2019}' . preg_quote($charlist, '~') . ']+~u', $string, $result) > 0) {
                if (array_key_exists(0, $result) === true) {
                    $result = $result[0];
                }
            }

            if ($format == 0) {
                $result = count($result);
            }

            return $result;
        }

        function word_count ($string) {
            $words_to_count = strip_tags($string);
            $pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\|\/|\-\-|:|\&|@)]+/";
            $words_to_count = preg_replace ($pattern, " ", $words_to_count);
            $words_to_count = trim($words_to_count);
            $total_words = count(explode(" ",$words_to_count)); 
            return $total_words;
        }

        ?> 
    </body>
</html>

您面临的主要问题是您 POST 转到另一个脚本,然后 header("location: index.php"); 回到 index.php。这会丢失所有 $_POST 变量,并且无法将它们添加到 header 重定向(浏览器 POST,而不是服务器 header 重定向)。

所以,你需要改变方向...

由于您已经将文本区域内容填充到 session 变量 $_SESSION['Text'] 中,您可以在 index.php:

上使用它
<textarea name="TextArea" ...otherstuff... ><?php 
      echo (!empty($_SESSION['Text']) ? htmlspecialchars($_SESSION['Text']) : '' );
      unset($_SESSION['Text']);// optionally clear after re-iterating it
?></textarea>       

您需要在 ProcessText.php 页面中说明一些注意事项:

  • session_start(); 移动到任何 html 或 echo 输出之前的最顶部。
  • header();exit; 之前添加 session_write_close();
  • 哎呀,你 header() 上面的所有 'html' 也需要去掉。

如果您不想使用 sessions... 因为一些专家告诉您它们非常不可靠且毫无用处:

A) POST 到 同一页面 将是 re-displaying 您的表格(即 index.php)

B) 设置处理所有提交的主分支脚本,但没有自己的 html。然后这将直接 include('index.php'); 您应该给哪个页面(因此 $_POST 变量将存在)。但是,此方法在设置所有脚本和 html 块时需要一些计划和纪律。

在您捕获错误集的位置 $_SESSION['textentered']。例如,如果您不想在数据库中复制值。 示例:

//condition that makes you echo back entered values when there is an error
if($rowexists){
$_SESSION['textentered']=$_POST['textentered'];
}

然后在您的文本区域中执行以下操作:

<textarea><?php if(isset($_SESSION['textentered']) && $_SESSION['textentered'] !=''){echo $_SESSION['textentered'];} ?></textarea>

这对我有用。