如何在不重新加载页面的情况下进行随机文本更改


how to make random text change without reloading the page

现在我有了这个脚本,它给用户一个随机单词。。然而,获取新词的唯一方法是刷新页面。。。

我希望能够设置单词在特定的时间间隔内更改,而不是重新加载页面或浏览器,但我不知道如何做到这一点,我一直在阅读,似乎无法理解

这是我的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页面上的javascript,它调用php代码

<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。

我会编写PHP文件,以便它返回一个JSON字符串。在中,我将编写一个函数,使用jQuery.get来解析PHP文件中的结果。然后使用seTimeout函数调用该函数。所以你的Javascript看起来像:

function getword(){
  $.get( "randomword.php", function( data ) {
  $( "body" )
    .append( "Word: " + data.word ) 
}, "json" );
}
setTimeout(getword, 2000);