php - 防止刷新重新加载数据而不重定向到新页面
问题描述
我有一个将评论写入文件的单页评论 php 网页。但在刷新时,它会不断重新发布最后的评论。如何将其编码为仅在按下提交按钮时才写入文件。谢谢你。
<?php
/*if($_POST)*/
if(isset($_POST['submit_btn'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
$handle = fopen("comments.php", "a");
fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
fclose($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Rolling Log</title>
<meta charset="uft-8">
</head>
<style>
body {
background-color: grey;
}
#top,#bottom {
margin: 0 auto;
width: 50%;
padding: 5px;
}
div {
border: 1px solid black;
background-color: white;
}
</style>
<body>
<div id="top">
<h1>Post a change mgmt comment</h1>
<form action="" method="POST">
Name: <br /> <input type="text" name="name"> <br />
Comment: <br /> <textarea rows="5" cols="70" name="comment"></textarea> <br /><br />
<input type="submit" name="submit_btn" value="Post comment">
</form>
</div>
<br>
<div id="bottom">
<h1>Other CM Comments</h1>
<?php include "comments.php"; ?>
</div>
</body>
</html>
解决方案
使用标题刷新功能:header("Refresh:0");
这是因为当您向同一页面发送请求时,如果您不使用 header 函数强制它们,则 headers 不会更改(并且会保留当前在文件中添加数据的请求)。
/*if($_POST)*/
if(isset($_POST['submit_btn']))
{
$name = $_POST['name'];
$comment = $_POST['comment'];
$handle = fopen("comments.php", "a");
fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
fclose($handle);
header("Refresh:0");
}
推荐阅读
- python - 如何从python中的字符中删除字符串?
- javascript - 在 AR.JS 中识别标记后重定向用户
- python - 将非常大的 csv 文件拆分为较小的文件
- python - Altair 更改边框颜色 LayerChart
- r - 如何在不删除R中的行的情况下将一列向下移动
- r - 多项回归的参考类别或类
- django-rest-framework - 如何从 unittest 重新生成 django 请求?
- sql - 如何通过UPDATE将数据从另一个表复制到空表中?
- node.js - 超级账本结构通道创建节点 SDK - 错误
- mongodb - 有什么方法可以在 mongoDB 中使用 $exists 和 $expr 吗?