Javascript 如何重新加载JSONObject内容
下面的代码从数据库动态生成json数据。生成数据时,它会将数据添加到特定的div中。如何使JSONObject的内容每30秒重新加载一次。这将使内容以近乎实时的方式显示变化Javascript 如何重新加载JSONObject内容,javascript,php,jquery,ajax,json,Javascript,Php,Jquery,Ajax,Json,下面的代码从数据库动态生成json数据。生成数据时,它会将数据添加到特定的div中。如何使JSONObject的内容每30秒重新加载一次。这将使内容以近乎实时的方式显示变化 <script> JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>; document.getElementById("today_visits").innerHTML=JSONObject.to
<script>
JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>;
document.getElementById("today_visits").innerHTML=JSONObject.todayVisits;
</script>
我试着用它来重新加载json数据
<script>
function load(){
JSONObject = <?php echo include_once('../includes/dashboard-stats.php'); ?>
document.getElementById("today_visits").innerHTML=JSONObject.todayVisits;
setTimeout("load()",9000);
}
</script>
函数加载(){
JSONObject=
document.getElementById(“今日访问”).innerHTML=JSONObject.todayVisits;
setTimeout(“load()”,9000);
}
更新了答案:
<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>
函数加载(){
变量颜色=[“#中交”、“#333333”、“#990099”];
var rand=Math.floor(Math.random()*colors.length);
$.getJSON(“../includes/dashboard stats.php”,{get:“stats”},函数(数据){
$(“#今日访问”).fadeOut().fadeIn().html(data.todayvisions).css(“背景色”,颜色[rand]);
});
}
$(函数(){
load();//在页面上加载。
设置间隔(负载,9000);
});
../includes/dashboard-stats.php的url与它所呈现的脚本所在页面的位置相关,我们可以执行以下操作:
setInterval(load, 5000);
function load() {
$.get('../includes/dashboard-stats.php', function(ReturnData) {
JSONObject = ReturnData
});
}
- 使用
setInterval
- 在函数
中,创建一个ajax请求以获取数据load
ReturnData
保存在触发./includes/dashboard stats.php
时生成的内容的输出(HTML)-尝试在浏览器中运行它,然后找到要使用的数据
编辑
- 删除注释后第1行的“load()”
$.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);
}):
您的最后一个代码看起来像代码,只是您需要在不使用任何PHP的情况下进行适当的ajax调用。为什么要用
jquery
标记此代码?如果您使用jquery,请查看它的ajax函数。这将不起作用,因为PHP只执行一次,因此它将每隔x秒以相同的内容+1“更新”,尽管我个人会在回调函数中设置超时,而不是使用间隔。为了安全起见。我如何添加fadein效果,以及在其变化时添加不同的背景色?应为setInterval(load,5000)代码>,没有大括号。我把它添加到我的网站上,我看不到任何数据。我怎样才能在第一次显示数据之前阻止9秒的延迟。在我看到数据之前,在页面上加载空白9秒
function loadStats(){
$.post( "../includes/dashboard-stats.php", { get:"stats" }, function(data) {
$("#today_visits").html(data.todayVisits);
}, "json");
}
$(function(){
loadStats();
setInterval(loadStats,9000);
}):