【问题标题】:Update PHP content every 5s using Ajax or Jquery使用 Ajax 或 Jquery 每 5 秒更新一次 PHP 内容
【发布时间】:2020-08-14 08:47:51
【问题描述】:

我试图每 5 秒更新一次我的 php 页面,以便新数据可以进入一个 .json 文件,所以基本上它的作用是,它从数据库中获取数据,并创建一个 .json 文件有了这些数据,我需要这个 php 文件每 5 秒更新一次,所以 .json 文件也在更新。
代码(JsonfileAPI.php):

<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
    function get_data()
    {
        $servername = "nps";
        $dBUsername = "nps";
        $dBPassword = "nps";
        $dBname = "nps";

        $conn = mysqli_connect($servername, $dBUsername, $dBPassword, 
        $dBname);

        if ($conn->connect_error){
        die ("Connection failed". $conn->connect_error);
        }

        $sql = "SELECT * FROM dados;";
        $result = mysqli_query($conn, $sql);
        $json_array = array();
        while($row = mysqli_fetch_assoc($result))
        {
            $json_array[] = array(
                'AutoIncrement'         =>       $row["AutoIncrement"],
                'Aparelho'         =>       $row["aparelho"],
                'Status'         =>       $row["Status"],
            );
        }
        return json_encode($json_array);
    }
    $file_name = 'dadosjson' . '.json';

    if (file_put_contents($file_name, get_data()))
    {
        echo $file_name. ' file created';
    }
    else 
    {
        echo 'There is some error';
    }
?>
<script>
$(document).ready(function () {
setInterval(function(){
    $.ajax({
        url: "JsonfileAPI.php",
        type: 'post',
        dataType: 'json',
        success: function(response) {
            $('.time').html(response);
        }
    });
    }, 5000);
});
</script>

【问题讨论】:

    标签: php jquery ajax refresh


    【解决方案1】:

    您可以在您的应用程序中使用此代码,我建议使用单独的文件,例如 index.php(用于您的 html 代码)和 action.php 用于 PHP 脚本。并且不需要 .json 文件。

    试试这个,在 index.php html 部分和 javascript 部分像这样

     $(document).ready(function () {
         setInterval(function(){
                $.ajax({
                    url: "action.php",
                    type: 'post',
                  //  dataType: 'json',
                    success: function(response) {
                       console.log(response);
                      $('.time').html(response);
                  }
                });
            }, 5000);
          });
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
    
        <div class="time">
        </div>
        </body>
    </html>

    那么你的action.php文件应该是这样的,

      <?php
        $localhost = "nps";
        $username = "nps";
        $password = "nps";
        $dbname = "nps";
    
        // db connection
        $connect = new mysqli($localhost, $username, $password, $dbname);
        // check connection
        if ($connect->connect_error) {
          die("Connection Failed : " . $connect->connect_error);
        } else {
         //  echo "Successfully connected".$dbname;
        }
    
        $sql = "SELECT * FROM dados";
        $result = $connect->query($sql);
    
        $output = array('data' => array());
    
        if ($result->num_rows > 0) {
          while ($row = $result->fetch_array()) {
          $output['data'][] = array(
          $row[0],
          $row[1],
          $row[2]
         );
        }
       }
       $connect->close();
    
       echo json_encode($output);
    

    我已经检查过了,它工作正常。认为这会有所帮助。

    【讨论】:

    • 嘿,谢谢你的帮助,但我正在做一个单独的 .json 文件,因为我正在使用 ESP32 从 .json 文件中读取信息,我为此提出了一个获取请求,将它仍然可以使用此代码吗?我应该把 javascript 放在 index.php 中吗?
    • 由于某种原因我的 action.php 没有更新,要更新问题,所以你可以看到
    • @NiltonSchumacherF 我假设该过程是从数据库中获取数据,然后每 5 秒在 html 中显示一次更新。不是吗?
    • 它应该做什么,它每 5 秒更新一次我的数据库中的信息,而不是每次都刷新页面,它作为响应获得的数据必须是 JSON 格式,所以我可以用我的 ESP32 阅读,我在 php 草图中遇到 JSON 格式问题,因为当我执行 GET 命令时,它没有正确读取 JSON 数组,这就是我制作 .json 文件的原因
    • 在 index.php 文件的 javascript 代码中,每 5 秒向 action.php 文件发送一个请求,然后将 json 数据响应到 index.php 中,您可以进入 html
    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多