首页 > 解决方案 > 使用 setInterval 分别显示 MySQL 表中的随机记录

问题描述

我希望每秒显示 5 个句子。当我在 RandomSentences 变量中列出每个句子时,以下代码有效:

(function() {
var timesRun = 0;
var runLimit = 5;
var RandomSentences = ['This is the first sentence', 'This is the second sentence', 'This is the third sentence', 'This is the fourth sentence', 'This is the fifth sentence'],
i = 0;

setInterval(function() {
timesRun += 1;
if (timesRun < runLimit) {

  $('#changing-word').fadeOut(function() {
    $(this).html(RandomSentences[i = (i + 1) % RandomSentences.length]).fadeIn();
  });
 }
}, 1000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="changing-word">Sentences go here</span>

但是,我有一张包含数千个句子的表格,我希望显示 5 个随机句子。我可以像这样选择这些记录:

SELECT sentences FROM table
ORDER BY RAND()
LIMIT 5

但是现在我如何将这 5 个随机记录放入 RandomSentences 变量中,以便我可以继续使用上面的 setInterval 每秒显示它们?

标签: jquerymysql

解决方案


推荐阅读