我有一个 php 代码,位于 div 中。它显示放置在 random.txt 文件中的随机文本。我想刷新这个 div,每隔 15 秒加载新文本,而不刷新 whoe 页面。 我找到了几种在不刷新页面的情况下重新加载 div 的解决方案,似乎可以使用 AJAX 或 JS 来完成,但它们只使用特定内容或特定文件刷新它,但是我不知道如何插入它代码并刷新。
这就是我的 div 的样子:
<div id="randomtext">
<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>
</div>
它会在每次刷新时向 div 加载随机文本。
我尝试用下面的JS刷新div,但它根本不起作用。抱歉,我不擅长。
<script>
var auto_refresh = setInterval(
function () {
var newcontent= '<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>';
$('#randomtext').html(newcontent);
}, 1000);
</script>
<div id="randomtext"></div>
提前致谢。
最佳答案
PHP 脚本和 Javascript 在不同的环境中执行。 (分别是您的服务器和用户的浏览器。)
您需要做的是将嵌入的 PHP 脚本移至单独的 PHP 文件中。并使用这样的东西:
content.php
<?php
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
?>
在 html 页面内
<script>
var auto_refresh = setInterval(
(function () {
$("#randomtext").load("path/to/content.php"); //Load the content into the div
}), 1000);
</script>
<div id="randomtext"></div>
jQuery Load 函数的文档:http://api.jquery.com/load/
关于javascript - 刷新包含 PHP 代码的 div,而不刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21174923/