下面的代码从数据库动态生成json数据。生成数据时,会将其添加到特定div。如何每隔30秒重新加载JSONObject的内容。这将使内容显示接近实时的变化。
<script>
JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>;
document.getElementById("today_visits").innerHTML=JSONObject.todayVisits;
</script>
以下是JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>;
JSONObject = {"todayEarnings":"2.60","todayVisits":"212","todayClicks":"36","todayLeads":"3","todayCalculateCR":"12%","todayEPC":"0.08","todayCTR":"17%","yesterdayEarnings":"0.40","yesterdayClicks":"35","yesterdayVisits":"148","yesterdayLeads":"1","yesterdayCalculateCR":"35%","yesterdayEPC":"0.03","yesterdayCTR":"24%","monthEarnings":"3.00","monthClicks":"75","monthVisits":"392","monthLeads":"4","monthCalculateCR":"19%","monthEPC":"0.05","monthCTR":"19%"}
1;
我尝试使用它来尝试重新加载json数据。
<script>
function load(){
JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>
document.getElementById("today_visits").innerHTML=JSONObject.todayVisits;
setTimeout("load()",9000);
}
</script>
答案 0 :(得分:2)
您的PHP代码仅运行一种类型这就是为什么结果显示相同。 每隔30秒使用Ajax调用并通过PHP文件从DB获取新数据。
// Jquery语法
$.post("Your PHP SCRIPT FILE PATH HERE", { PARAMS you want to pass }, function( Get DATA FROM PHP FILE ) {
// HERE IS YOU Operation
},"DATA FORMAT");
==================================
//代码示例
function loadStats(){
$.post( "../includes/dashboard-stats.php", { get:"stats" }, function(data) {
$("#today_visits").html(data.todayVisits);
}, "json");
}
$(function(){
loadStats();
setInterval(loadStats,9000);
}):
答案 1 :(得分:1)
更新回答:
<script>
function load() {
var colors = ["#CCCCCC","#333333","#990099"];
var rand = Math.floor(Math.random()*colors.length);
$.getJSON("../includes/dashboard-stats.php", { get:"stats" },function(data) {
$("#today_visits").fadeOut().fadeIn().html(data.todayVisits).css("background-color", colors[rand]);
});
}
$(function() {
load();//on the page load.
setInterval(load,9000);
});
</script>
../includes/dashboard-stats.php的网址是相对于其所在脚本所在页面的位置
答案 2 :(得分:0)
使用jQuery library,我们可以做类似的事情;
setInterval(load, 5000);
function load() {
$.get('../includes/dashboard-stats.php', function(ReturnData) {
JSONObject = ReturnData
});
}
setInterval
load
中,创建一个获取数据的ajax请求。 ReturnData
保存触发../includes/dashboard-stats.php
时生成的内容的输出(HTML) - 尝试在浏览器中运行它,然后找到您想要使用的数据的位置。
"load()"