javascript - 一次仅显示数据库中的一项,然后循环显示其他项

标签 javascript php jquery sql

我正在尝试设置一个页面,一次显示新闻数据库中的一行信息。它将显示第一行大约 10 秒,然后在相同的时间内切换到下一行新闻。我找到了五年前的一个答案,似乎它可以工作,但每次我尝试运行它时,我的一个变量由于未定义而变得不可读。完整代码如下:

<?php
  include('include/sqlsettings.php');
  $mysqli_conn = mysqli_connect($mysqli_host, $mysqli_user, $mysqli_pass, $mysqli_db);
  $query = 'SELECT * FROM news';
  $rs = mysqli_query($mysqli_conn, $query);
  $info = array();

  while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)){
    array_push($info, array('title' => $row['id'],
                            'news' => $row['news'],
                            'location' => $row['location']));
    $infoData = json_encode(array('info' => $info));
    file_put_contents('info.json', $infoData);
  }
?>
<html>
  <head>
  </head>
  <body>
    <ul></ul>
  </body>
  <script src='/libs/js/jquery/jquery-3.2.1.min.js'></script>
  <script>
    var i = 0,
        d = null,
        x = null,
        interval = 3000;

    $(document).ready(function(){
      fetch();
    });

    function fetch(){
      // get the data *once* when the page loads
      $.getJSON('info.json', function(data){
        // store the data in a global variable 'd'
        d = data.result;
        // create a recurring call to update()
        x = setInterval(function(){
          update()
        }, interval);
      });
    }

    function update(){
      // if there isn't an array element, reset to the first once
      if (!d[i]){
        clearInterval(x);
        i = 0;
        fetch();
        return;
      }
      // remove the previous items from the page
      $('ul').empty();
      // add the next item to the page
      $('ul').append(
        '<li>' + d[i]['title']
        + '</li><li>' + d[i]['news']
        + '</li><li>' + d[i]['location']
        + '</li>'
      );
      // increment for the next iteration
      i++;
    }
  </script>
</html>

代码错误于 if(!d[i])反击 Uncaught TypeError: Cannot read property '0' of undefined at update (<file>.php:33)其中 d 应该定义为 json 数据,以便我可以循环遍历它。我不完全确定我做错了什么。

最佳答案

您正在将 d 分配给 data.result。如果dundefined,那是因为data.result未定义。如果 data.result 可能未定义,请考虑执行以下检查。

if(d && !d[i])

这将确保在检查索引之前定义d

关于javascript - 一次仅显示数据库中的一项,然后循环显示其他项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60417429/

相关文章:

javascript - jquery 选择器帮助

php - 检测在线用户 : PHP

php - SQL语句不返回任何内容

php - 检测模型的变化; php yii 框架

javascript - 使用 jQuery .html 插入 javascript

javascript - 哪种ajax响应方式更好?

php - 如果我们希望先执行 javascript 然后执行 php post 方法(即提交)该怎么办

javascript - 如何将 JSON 转义字符串转换为纯 HTML 兼容字符串

jquery - 如何使用CSS设置输入类型文件的样式

javascript - ng-click 在 AngularJS 中不触发,而 onclick 却触发