[英]Auto refresh included PHP file inside a DIV
I have a file called messages.php which runs SQL queries to a database and displays results in a $res
variable 我有一个名为messages.php的文件,它将SQL查询运行到数据库并在
$res
变量中显示结果
My menu.php page I used 我使用的menu.php页面
include 'messages.php';
And then: 然后:
<div id="msgs">
<?php echo $res; ?>
</div>
So this displays all the data in the $res
variable from the messages.php page in a div on menu.php 因此,这将显示来自menu.php上div中的messages.php页面的
$res
变量中的所有数据
How can i make this automatically refresh so any new data in the $res
variable displays without having to refresh the menu.php page? 如何让它自动刷新,以便显示
$res
变量中的任何新数据而无需刷新menu.php页面?
First Remove include 'messages.php'; 首先删除包括'messages.php'; Then remove echo $res;
然后删除echo $ res; from div and put it in the last line of messages.php
来自div并将其放在messages.php的最后一行
and try the following code after including the jquery file 并在包含jquery文件后尝试以下代码
<script>
jQuery().ready(function(){
setInterval("getResult()",1000);
});
function getResult(){
jQuery.post("messages.php",function( data ) {
jQuery("#msgs").html(data);
});
}
</script>
<div id="msgs">
</div>
This requires the jQuery library. 这需要 jQuery库。 It could be done in pure JS , but if you're a JS beginner I recommend using jQuery .
它可以在纯JS中完成,但如果你是JS 初学者,我推荐使用jQuery 。
function reload_messages(){
$.get("messages.php", function(data) {
$("#id").html(data);
});
}
You will then need to call reload_messages, for example: 然后,您需要调用 reload_messages,例如:
<a href="javascript:reload_messages();">reload messages</a>
If you want to expand on the .get method, check out this page: https://api.jquery.com/jQuery.get/ 如果要扩展.get方法,请查看此页面: https : //api.jquery.com/jQuery.get/
If you want it to refresh on an interval, you can make use of setInterval
如果要在一个间隔上刷新它,可以使用
setInterval
setInterval( refreshMessages, 1000 );
1000
is 1000 milliseconds, so 1 second, change this to how you like. 1000
是1000毫秒,所以1秒,改变你喜欢的方式。
So every 1 second it triggers the function refreshMessages: 所以每1秒触发一次函数refreshMessages:
function refreshMessages()
{
$.ajax({
url: 'messages.php',
type: 'GET',
dataType: 'html'
})
.done(function( data ) {
$('#msgs').html( data ); // data came back ok, so display it
})
.fail(function() {
$('#msgs').prepend('Error retrieving new messages..'); // there was an error, so display an error
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.