我有一个简单的HTML表单:
<form action="index.php" method="post">
<textarea id="question" name="question"></textarea>
<input type="submit"/>
</form>
我喜欢的程序就像这里描述的那样:
在文本区域中键入内容,然后单击“提交”,显示结果:
[... the only text area got blank and be ready for new input ...]
Question 1: Something typed firstly
在上面的文字区域输入其他内容并提交,显示结果:
[... the only text area got blank and be ready for new input ...]
Question 1: Something typed firstly
Question 2: Something typed secondly
等等......
[... the only text area got blank and be ready for new input ...]
Question 1: Something typed firstly
Question 2: Something typed secondly
...
Question n: Something typed at the n time
有没有人有想法或者只能使用HTML和PHP给我提示如何做到这一点?
非常感谢!
答案 0 :(得分:2)
如果您不断回显id值和刚刚提交的值,则可以使用隐藏的输入。 (另请注意我如何在提交中添加名称)
<form action="index.php" method="post">
<?php
if(isset ($_POST['submit']) {
$oldAnswers = array ();
if(isset($_POST['oldAnswers']) && is_array ( $_POST['oldAnswers'])) {
$oldAnswers = $_POST ['oldAnswers'];
}
if (isset ($_POST ['question']))
$oldAnswers[] = $_POST ['question'];
for($i = 0, $j = 1; $i < count (oldAnswers); $i++, $j++) {
$answer = $oldAnswers [$i];
// display your "previously written" message
echo 'Question ' . $j . ': ' . $answer . "<br>\n";
// echo out hidden inputs
echo '<input name="oldAnswers[]" type="hidden" value="' . $answer . '">';
}
}
?>
<textarea id="question" name="question">< /textarea>
<input name="submit" type="submit">
</form>
在名称中查看oldAnswers后面[]
的内容如何?那将告诉php它是一个数组并且易于处理。
答案 1 :(得分:1)
如果您不想将值放在数据库中,可以使用会话
session_start();
位于页面顶部,
<?php
if( $_SESSION['counter'] > 0 ) $_SESSION['texts'] = $_SESSION['texts'] . "<br />Question " . $_SESSION['counter'] . ": Something " . $_POST['question'];
$_SESSION['counter']++;
?>
<?php echo $_SESSION['texts']; // put this in a div where you want to see them ?>
只有在浏览器关闭时才会清除。
这是一个非常粗略的大纲,但您可以查看有关会话的教程以及如何使用它们。
您还需要在脚本底部添加一个计数器来添加数字。
$_SESSION['counter']++;
使用隐藏输入替换没有数组或for循环的会话。
<?php
$counter = $counter + (int) $_POST['counter']; // (int) helps sanitise this by forcing type change to integer - any text would be converted to 0
//echo $counter; // for trackng
$texts = $_POST['texts']; // MUST be sanitized and escaped for mysqli
if($counter > 0) $texts = $texts . "<br />Question " . $counter . ": Something " . $_POST['question'];
$counter++;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea id="question" name="question"></textarea>
<input type="hidden" name="texts" id="texts" value="<?php echo $texts;?>" />
<input type="hidden" name="counter" id="counter" value="<?php echo $counter; ?>" />
<input type="submit"/>
</form>
<?php echo $texts; // put this in a div where you want to see them ?>
不清除post变量就不要使用此代码,否则黑客会被黑客攻击。请参阅preg_replace()
和php.net上的其他帖子