【问题标题】:Display only one item from a database at a time and loop through others to display一次只显示数据库中的一项并循环显示其他项目
【发布时间】:2020-06-10 12:48:16
【问题描述】:

我正在尝试设置一个页面,该页面一次显示来自新闻数据库的一行信息。它将显示第一行大约 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 (&lt;file&gt;.php:33) 其中 d 应该被定义为 json 数据,这样我就可以遍历它。我不完全确定我做错了什么。

【问题讨论】:

    标签: javascript php jquery sql


    【解决方案1】:

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

    if(d &amp;&amp; !d[i])

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

    【讨论】:

    • 谢谢!这帮助我弄清楚,因为相同的文档正在创建并尝试引用它不起作用的 JSON 文件。它们现在位于单独的文件中,没有更多错误,但仍然不是我想要的。不过绝对有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2021-08-31
    • 2013-12-26
    • 2020-03-05
    相关资源
    最近更新 更多