【发布时间】:2020-02-09 14:19:32
【问题描述】:
我有一个 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 中
【问题讨论】:
-
在这种情况下使用 Ajax 无可避免。您应该使用 Ajax 并尝试解决您遇到的问题(“它会加载整个页面”)。分享您的 ajax 版本代码。