应该用新的数据库信息更新页面的ajax函数正在按其应有的方式工作

时间:2018-08-12 21:35:33

标签: javascript php jquery html ajax

我正在尝试使用PHP创建一个基本的聊天应用程序,我希望页面每5秒钟更新一次,新消息一旦发送就存储在Mysql数据库中。这是我的“ webmessenger.php”:

<html>
<head>
<script type="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<style>
#content{
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
#container{
  margin: 0 auto;
}
}
</style>
  <body>
<div id = "container">

</div>
    <form action="webmessenger.php" method="post">
      <input type="text" name = "message"/>
     <input type = "submit" value = "send"/>
    </form>
  </body>
<script language="javascript" type="text/javascript">
function loadlink(){
    $('#container').load('update.php',function () {
         $(this).unwrap();
    });
}

loadlink(); // This will run on page load
setInterval(function(){
    loadlink() // this will run after every 5 seconds
}, 5000);
</script>
<?php
include("update.php");
$mysqli = new mysqli("SERVER IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST'){ 
$message = $_POST['message'];
$sql = "INSERT INTO `messages` (text) VALUES ('$message')";
$mysqli->query($sql); 
}
?>
</html>

此代码成功打印出搜索栏,并且是自从我包括update.php以来,数据库中最后一个已知的条目,后者与数据库联系并打印包含消息的每一行。但是,使用ajax进行的定期刷新不会发生,因为当您打开两个窗口并在一个窗口上发送消息时,它永远不会在另一个窗口上弹出。

这是update.php供参考:

<?php
$mysqli = new mysqli("DB IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$sql = "SELECT * FROM `messages`";
 
$res = $mysqli->query($sql);

 
if($res->num_rows > 0){
 while($row = $res->fetch_assoc()){
$rownum=$row["id"];

 echo $row["text"]."<br />";

 }

}
else
{
 echo "No Record Found!";
}
?>

如果有人可以帮助我,让我知道为什么该功能无法正常运行,将不胜感激。预先感谢。

0 个答案:

没有答案