好的,所以这是我的页面(为练习重新创建的基本模板): http://puu.sh/fRn4b/6d83015087.png
它全部是静态的,禁止形式。
我尝试对所述表单执行的操作是将输入的内容显示在下面的小灰框中(它有溢出设置,因此一旦填满就会启用滚动)。
我从这开始:
<form action="index.php" method="post">
<input type="text" name="name" placeholder="Enter your name" required><br>
<textarea name="comment" id="comments" rows="10" required placeholder="Enter your thoughts"></textarea><br>
<input type="submit" name="submit">
</form>
if (isset($_POST['name']) && isset($_POST['comment'])) {
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$fullcomment = "<h2>".$name."</h2><p>".$comment."</p>";
echo $fullcomment;
}
这很有效,而且用css看起来很不错。但是它只会发布一条评论,并且评论会在重新加载时丢失。我希望它坚持下去。那么接下来的尝试是:
if (isset($_POST['name']) && isset($_POST['comment'])) {
$file ="./index.php";
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$fullcomment = "<h2>".$name."</h2><p>".$comment."</p>";
file_put_contents($file, $fullcomment, FILE_APPEND);
}
现在提交表格后,什么都不会发生(包括没有错误)。是不是可以在文件上使用file_put_contents表示函数(?)在?因为我尝试将$文件更改为&#34; ./ index.txt&#34;这很有效,它创建了一个新文件并在其中添加了表单内容。
你可能会说我对此非常陌生。这是我的学习。我接受了新的东西,我想到了我可以应用它们的方法,即使这些方法不是最有效的方法。
任何帮助都会非常感谢你! 它确实有效,但它在文档末尾添加内容,而不是在注释框中添加内容。必须要找到不同的方法。
编辑2:我想我可以从index.txt进行故障排除并将其添加到.php文件中,但这似乎有点迂回。
编辑3:这是有效的yuhp。虽然现在刷新index.php导致重复最后输入的表单内容,这是相当烦人的。解决方案是否会在代码运行后重置变量?
答案 0 :(得分:2)
您可以使用Ajax来解决此问题,但如果您不熟悉它,可以尝试一下:
$file ="./comments.txt";
// When you the page is loaded, get the comments from 'comments.txt'
$fullcomment = file_get_contents($file);
if (isset($_POST['name']) && isset($_POST['comment'])) {
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$fullcomment = "<h2>".$name."</h2><p>".$comment."</p>";
file_put_contents($file, $fullcomment, FILE_APPEND);
}