jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。在线留言系统通常用于网站或应用中,允许用户提交反馈或消息,这些消息会被存储在数据库中以便后续查看和管理。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在线留言系统</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>在线留言板</h1>
<form id="messageForm">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="message">留言:</label>
<textarea id="message" name="message" required></textarea><br><br>
<button type="submit">提交</button>
</form>
<div id="messages"></div>
<script>
$(document).ready(function() {
$('#messageForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'submit_message.php',
method: 'POST',
data: {
name: $('#name').val(),
message: $('#message').val()
},
success: function(response) {
$('#messages').append('<p>' + response.name + ': ' + response.message + '</p>');
$('#name').val('');
$('#message').val('');
}
});
});
// 加载已有留言
$.ajax({
url: 'get_messages.php',
method: 'GET',
success: function(messages) {
messages.forEach(function(message) {
$('#messages').append('<p>' + message.name + ': ' + message.message + '</p>');
});
}
});
});
</script>
</body>
</html>
submit_message.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$name = $_POST['name'];
$message = $_POST['message'];
$sql = "INSERT INTO messages (name, message) VALUES ('$name', '$message')";
if ($conn->query($sql) === TRUE) {
echo json_encode(array("name" => $name, "message" => $message));
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
get_messages.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "SELECT name, message FROM messages";
$result = $conn->query($sql);
$messages = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$messages[] = $row;
}
}
echo json_encode($messages);
$conn->close();
?>
通过以上步骤和代码示例,你可以实现一个基本的在线留言系统,并了解其中涉及的基础概念和相关技术。
领取专属 10元无门槛券
手把手带您无忧上云