我目前正在尝试创建一个聊天网站,该网站会接受用户的输入并将其显示在输入框上方的聊天框中,以便连接到该网站的每个人都可以看到它,但是我需要使用AJAX来做到这一点,不需要每次刷新页面
我对后端Web开发非常陌生,因此,如果这是一个不好的问题,我感到非常抱歉,到目前为止,我有以下代码,但每次运行它似乎都不起作用:
Debate.php:
<?php
session_start();
$message = '';
$user = ($_SESSION['sessionUsername']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$connect = new mysqli('localhost', 'root', '', 'chatBase');
$message = mysqli_escape_string($connect, $_POST['message']);
$message_query = "INSERT INTO chatlog (user, message) VALUES('$user', '$message')"; //Inserts the message and username into the database//
mysqli_query($connect, $message_query);
}
?>
<html>
<head>
<title>Debate</title>
<link rel=stylesheet href=styles.css>
<h1 class="indexTitle">Headline</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function retrieveMessages() {
$.get("./read.php", function(data) { //executes the PHP code written in the 'read.php' file//
$chatbox.html(data); //inserts the fetched data into the div with the id 'chatbox'//
});
}
setInterval(function() {
retrieveMessages(); //executes the 'retrieveMessages' function every second//
}, 1000;
</script>
</head>
<body>
<div class="textBoxSquare" id="chatbox"></div>
<form class="form-inline" action="Debate.php" method="post">
<input class="textBoxInput" type="text" name="message" id="message">
<input class="textBoxSubmit" type="submit" value="Submit">
</form>
</body>
</html>
read.php:
<?php
$connect = new mysqli('localhost', 'root', '', 'chatBase');
$query="SELECT * FROM chatlog ORDER BY messageID ASC";
mysqli_query($connect, $query);
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["user"];
$text=$row["message"];
echo "<p>$user: $message</p>\n";
}
?>
答案 0 :(得分:0)
为此替换脚本:
function retrieveMessages() {
$.get("./read.php", function(data) {
var data = JSON.parse(data); //Parses the data from jquery to a variable.
document.getElementById("chatbox")[0].innerHTML = data; //Sets the variable to the innerHTML of that DIV ID.
});
}
setInterval(function() {
retrieveMessages();
}, 1000;