javascript 自动刷新包含在 DIV 中的 PHP 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21600166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto refresh included PHP file inside a DIV
提问by
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
因此,这将$res
在 menu.php 上的 div 中的 messages.php 页面中显示变量中的所有数据
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 页面的情况下显示变量中的任何新数据?
回答by Sarath
First Remove include 'messages.php'; Then remove echo $res; from div and put it in the last line of messages.php
首先删除包含'messages.php'; 然后删除 echo $res; 从 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>
回答by C?????N????
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
});
}
回答by S..
This requiresthe jQuerylibrary. It could be done in pure JS, but if you're a JS beginnerI recommend using jQuery.
这需要在jQuery的库。它可以在纯 JS 中完成,但如果您是 JS初学者,我建议您使用jQuery。
function reload_messages(){
$.get("messages.php", function(data) {
$("#id").html(data);
});
}
You will then need to callreload_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/