[英]How to use setInterval() when there's a param?
I'm trying to get a single div on a php page to refresh every 5 seconds. 我正在尝试在php页面上获取一个div,以每5秒刷新一次。
In HTML I have: EDIT: NEW SCRIPT FUNCTION 在HTML中,我具有:编辑:新脚本功能
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'game.php',
success:function(data){
$("#read_chat").html(data);
}
});
}
setInterval(callAjax, 5000);
});
</script>
And the function (in a php block) I'm trying to refresh is: 我想要刷新的功能(在php块中)是:
echo" <div class='read_chat' >";
function get_messages($db){
//get messages
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
//display messages
foreach ($messages as $row) {
//display each message in row
if ( $row['character_name'] == NULL){
echo "<div class='left'>" . $row['user_name'] . ": </div>";
}
else {
echo "<div class='left'>" . $row['character_name'] . ": </div>";
}
echo "<div class='center'>" . $row['message'] . "</div>";
echo "<div class='right'>" . $row['time'] . "</div>";
}
}
echo "</div>";
The display of this is only the CSSed block without any content. 此显示仅是CSSed块,没有任何内容。 If I just call get_messages($db) all the chat from the database loads.
如果我只调用get_messages($ db),则所有来自数据库的聊天都会加载。 How do I make this div refresh automatically?
如何使该div自动刷新? Thanks!
谢谢!
EDIT: The name of the file is "game.php" and the php function is "get_messages()". 编辑:文件的名称是“ game.php”和php函数是“ get_messages()”。
For the record I looked at: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/ 对于记录,我查看了: http : //www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
and 和
Javascript Java脚本
setTimeout(function(){
$.ajax({url: "get_message.php", success: function(result){
var num_records = result.length,
i,
content;
for(i=0;i<num_records;i++){
if (result[i]['character_name'] !== null){
content += "<div class='left'>" + result[i]['character_name'] +": </div>";
}
else{
content += "<div class='left'>" + result[i]['user_name'] +": </div>";
}
content += "<div class='center'>" + result[i]['message'] + "</div><div class='right'>" + result[i]['time'] + "</div>";
}
$('.read_chat').html(content);
}});
}, 5000);
get_message.php get_message.php
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
$response = array();
foreach ($messages as $row) {
$response[] = $row;
}
echo json_encode($response);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.