javascript - 刷新包含 PHP 代码的 div,而不刷新页面

标签 javascript php html refresh

我有一个 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/

相关文章:

php - 如何使用 PHP 和 ffmpeg 在后台转换视频

javascript - 目标页面在没有浏览器页面加载的情况下更改其 URL。如何让我的用户脚本仅在该站点的选定页面上触发?

php - 用于 PHP session 的 mySQL 和 memcached?

javascript - WebUI Popover 无法使用 html 元素设置标题

php - 简单的 PHP MySQL 查询分组任务

javascript - 使用 javascript 正则表达式自动链接 URL

html - CSS垂直白线问题Chrome和Opera

jquery - 将 fullPage.js 添加到 Foundation

javascript - jQuery:单击复选框更改图像

javascript - 如何使用 jQuery/Javascript 更改 gridview 中的 <tr> 属性