javascript - 如何自动刷新我的 php 聊天脚本?

标签 javascript php html mysql

当 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>";
    }

    ?>

任何帮助将不胜感激,谢谢! :)

最佳答案

您可以使用 setIntervaljQuery 库 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/

相关文章:

javascript - 将字符串转换为日期及其实际日期格式

javascript - 从浏览器 : How to feature-detect "Intent" support? 启动 Android 应用程序

javascript - 页面重新加载时指定页面保持选中状态

javascript - 根据选择值更改表单操作 - 使用 JavaScript

php - Symfony 4 - 路由 : "The requested URL was not found on this server"

php - 准备好的陈述 - 是的,我知道这是一个真正讨论过的话题

javascript - 将多个字符串和文本连接成一个字符串 - Blogger Javascript

java - Java SWT 中是否支持 HTML5?

php - 以 json 对象形式传递时间戳值以填充流程图

html - 如果有子列表css,如何水平对齐列表