我有一个index.php和一个data.php文件。 我使用data.php从数据库(用于存储消息)中获取数据,并使用index.php将获取的数据映射到div .messages_container中。
index.php的代码
<?php
include("data.php");
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<meta name="viewport">
<title>title</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<noscript>Enable Javascript to access the full functionality of the website.</noscript>
</head>
<body>
<div class="header"><h1 id="main_header_text">forum</h1></div>
<div class="send_message">
<form action="data.php" method="POST">
<input type="text" name="usr" placeholder="name">
<input type="text" name="msg" placeholder="message">
<input type="submit" value="send">
<span class="send_error_span"><?php echo $send_error; ?></span>
</form>
</div>
<div class="messages_container">
<?php
foreach ($datas as $data) {
echo $data["id"] . " > <span class='username_in_display'>" . $data["sender"] . "</span>" . " " . "<span class='message_in_display'>" . $data["message"] . "</span>" . "<br>";
}
if(!$datas) {
echo "no messages yet.";
}
?>
</div>
</body>
<script>
setInterval(
function() {refresh();}, 1000
);
function refresh() {
//something there maybe?
}
</script>
</html>
这是data.php
<?php
include("config.php");
$conn = new mysqli($servername, $username, $pass, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "select id, ifnull(sender, 'anonymous') as sender, message from messages;";
$res = $conn->query($sql);
$datas = array();
if($res->num_rows > 0) {
while($row = $res->fetch_assoc()) {
$datas[] = $row;
}
}
$send_error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(!empty($_POST["msg"])) {
$n = $conn->real_escape_string($_POST["usr"]);
if($n == "") {
$n = "anonymus";
}
$m = $conn->real_escape_string($_POST["msg"]);
if($conn->query("insert into messages (sender, message) values ('$n', '$m');") === TRUE) {
} else {
echo "error: " . $conn->error;
}
} else {
$send_error = "<br><br>empty message!";
}
unset($_POST);
header("Location: index.php");
exit;
}
$conn->close();
?>
它工作正常,但是只有在我发送消息或刷新页面后才刷新。我希望它每5秒钟刷新一次,因此我不需要每次都手动刷新来查看新消息。我也不想刷新整个页面,只需重新运行PHP脚本部分即可以某种方式获取数据库数据。
我尝试使用AJAX,但问题是,一旦调用data.php,它将整个页面加载到messages_container div中
答案 0 :(得分:0)
您可以使用ajax从服务器端重新加载数据,但这将使客户端过载,并在客户端使用过多资源。
解决方案是使用套接字。
套接字是一种抽象,应用程序可以通过它来发送和接收数据,其方式与打开文件允许应用程序将数据读写到稳定存储器的方式几乎相同。套接字允许应用程序“插入”网络,并与也插入同一网络的其他应用程序通信。由一台计算机上的应用程序写入套接字的信息可以由另一台计算机上的应用程序读取,反之亦然。
您可以在此处了解更多信息:https://socket.io/