现在我有这个脚本,可以为用户提供一个随机单词.. 然而,获得新单词的唯一方法是刷新页面...
我希望能够将单词设置为以特定的时间间隔更改,而不必重新加载页面或浏览器,但我不知道该怎么做,而且我一直在阅读,似乎无法弄清楚
这是我的 php 代码
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
* If you prefer you can list quotes that RanTex will choose from here.
* In this case set above variable to $settings['text_from_file'] = '';
*/
$settings['quotes'] = array(
'First quote',
'Multi
line
quote',
'Second quote',
'Third quote',
'Some text with <b>HTML</b> code!',
'Any single quotes \' must be escaped with a backslash',
'A quote with a <a href="http://www.phpjunkyard.com">link</a>!'
);
/*
* How to display the text?
* 0 = raw mode: print the text as it is, when using RanTex as an include
* 1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type'])) {
$type = intval($_GET['type']);
} else {
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file']) {
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes'])) {
$txt = $settings['quotes'][array_rand($settings['quotes'])];
} else {
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type) {
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array(
"\n",
"\r"
), '', $txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\'' . addslashes($txt) . '\')';
} else {
echo $txt;
}
?>
这是我的 .html 页面上调用 php 代码的 javascript
<script type="text/javascript" src="randomword.php?type=1"></script>
现在,每次页面重新加载时,我都会收到一个新单词,但我希望该单词每 5 秒更改一次,而无需刷新页面......任何人都可以告诉我我的代码应该是什么样的吗?
最佳答案
尝试这样的事情:
在 HTML 中添加一个标签,如下所示:<div id="myrandomtext"></div>
您希望它显示在哪里,然后通过这段 JavaScript 到达您的网站:
setInterval(function() {
$("#myrandomtext").load("randomword.php?type=1");
}, 5000);
5000 是 5 秒。您可以将其更改为您想要的值(1 秒 = 1000)。 您需要更改:
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
至
echo $txt;
并删除<script type="text/javascript" src="randomword.php?type=1"></script>
注意:这使用 jQuery。
关于javascript - 如何在不重新加载页面的情况下进行随机文本更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250644/