基于ajax的web聊天室的代码
时间: 2023-12-14 21:04:50 浏览: 68
以下是一个基于ajax的web聊天室的示例代码,仅供参考:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Ajax Chat Room</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div id="chat-box" style="border: 1px solid #ccc; height: 300px; overflow-y: scroll;"></div>
<input type="text" id="message" placeholder="Type your message here...">
<button id="send">Send</button>
<script src="chat.js"></script>
</body>
</html>
```
JavaScript代码(chat.js):
```javascript
$(document).ready(function(){
// 显示聊天记录
function displayChat(){
$.ajax({
url: 'display_chat.php',
type: 'POST',
success: function(data){
$('#chat-box').html(data);
}
});
}
displayChat(); // 页面加载时显示聊天记录
// 发送消息
$('#send').click(function(){
var message = $('#message').val();
if(message != ''){
$.ajax({
url: 'send_message.php',
type: 'POST',
data: {message: message},
success: function(){
displayChat();
$('#message').val('');
}
});
}
});
// 每隔5秒自动刷新聊天记录
setInterval(function(){
displayChat();
}, 5000);
});
```
后端PHP代码(display_chat.php):
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chatroom";
$conn = new mysqli($servername, $username, $password, $dbname);
// 获取聊天记录
$sql = "SELECT * FROM messages ORDER BY id DESC";
$result = $conn->query($sql);
// 显示聊天记录
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>" . $row['username'] . ": " . $row['message'] . "</p>";
}
} else {
echo "No messages yet!";
}
$conn->close();
?>
```
后端PHP代码(send_message.php):
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chatroom";
$conn = new mysqli($servername, $username, $password, $dbname);
// 获取发送的消息
$message = $_POST['message'];
// 将消息保存到数据库
$sql = "INSERT INTO messages (username, message) VALUES ('user', '$message')";
$conn->query($sql);
$conn->close();
?>
```
其中,`display_chat.php`用于获取聊天记录并在前端显示,`send_message.php`用于接收前端发送的消息并将其保存到数据库中。这些代码需要根据具体的需求和环境进行修改和调整。
阅读全文