当 mysql 数据更改时,我无法让我的 php 聊天脚本自动刷新。我做了很多研究,似乎很多其他人的解决方案比我需要的更复杂(我正在寻找一些非常基本的东西)。
我不知道任何 javascript,所以如果涉及 js,将不胜感激。
这是我创建的 php 脚本。它正在运行(至少对我而言)。
include 'connect2.php';
echo "
Enter a Message:
<form method=post action='' name=chat>
<input type=text name=message>
<input type=submit name=chat value=Submit>
</form>
";
if (isset($_POST['chat'])) {
$message = $_POST['message'];
mysql_query("INSERT INTO chat set message='$message',user='$_SESSION[username]'");
}
$sql = "select * from chat order by id desc limit 15";
$result = mysql_query($sql) or die ("An error has occured with in the database.");
while ($data = mysql_fetch_assoc($result)) {
$db_message = $data['message'];
$db_user = $data['user'];
echo "$db_user : $db_message <br>";
}
?>
任何帮助将不胜感激,谢谢! :)
最佳答案
您可以使用 setInterval
和 jQuery
库 ajax 函数来检查它。
例如,用jQuery
做起来很简单:
$(document).ready(function() {
// check once in five seconds
setInterval(function() {
$.get('/script.php', {do: 'new_messages'}, function(response) {
if(response == 1) {
window.location.reload();
}
});
}, 5000);
});
服务器上某处:
if(isset($_GET['do']) && $_GET['do'] == 'new_messages') {
// some your code that detects if there's any new messages, and sets
// $there_are_new_messages to true, if there's any
...
if($there_are_new_messages) {
echo 1;
exit; // avoid further output
}
}
请记住,要使其正常工作,您需要确保在 ajax block 之前没有输出,因为您可能会得到意想不到的结果。
还要考虑到使用输出来向您的脚本显示一切正常根本不是一个好习惯。更好的方法是设置带有相应响应代码的 HTTP header 。
关于javascript - 如何自动刷新我的 php 聊天脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19645951/