gpt4 book ai didi

javascript - 如何使用 PHP 和 JQuery AJAX 在
标签中检索和插入 MySQL 数据?

转载 作者:行者123 更新时间:2023-11-29 16:13:45 25 4
gpt4 key购买 nike

我目前正在尝试创建一个聊天网站,该网站接受用户的输入并将其显示在输入框上方的聊天框中,以便连接到该网站的每个人都可以看到它,但我需要使用 AJAX 来实现这一点,所以页面不需要每次刷新

我对后端 Web 开发非常陌生,所以如果这是一个不好的问题,我很抱歉,到目前为止我有以下代码,但每当我运行它时它似乎都不起作用:

辩论.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>

读取.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";
}
?>

最佳答案

将您的脚本替换为:

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;

关于javascript - 如何使用 PHP 和 JQuery AJAX 在 <div> 标签中检索和插入 MySQL 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com