Я пытаюсь настроить страницу, которая отображает одну строку информации из базы данных новостей за раз. Он будет отображать первую строку в течение примерно 10 секунд, а затем переключаться на следующую строку новостей в течение той же продолжительности. Через пять лет я нашел ответ go, который выглядел так, как будто он будет работать, но каждый раз, когда я пытаюсь запустить его, одна из моих переменных становится нечитаемой из-за того, что она не определена. Полный код ниже:
<?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>'
);
// incriment 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 данные, чтобы я мог l oop через них. Я не совсем уверен, что я делаю неправильно.