我试图通过ajax拉出mysql表的最新条目,并将其显示为div内的html内容。我有ajax和php正常运行,我唯一的问题是我想查询新条目并在循环内的时间间隔堆栈结果我遇到了两个问题:让数据表现得像正常javascript字符串,并使循环只返回唯一条目。
update.php文件
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax请求循环:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
答案 0 :(得分:3)
问题在于你SELECT * FROM conversations
继续请求整个表 - 尽管你只选择最后一个。
您的代码需要记住已加载的评论,并且只能获得比此更新的评论。
例如,假设您的主键是增量,请执行SELECT * FROM conversations WHERE convid > ?
。将?
替换为已加载的最新评论。如果您是第一次加载,请执行SELECT * FROM conversations
您可以将使用request参数显示的最后一条评论ID传递到update.php
。此外,我建议以JSON格式返回数据,以便您可以返回注释和ID的集合并轻松解析
答案 1 :(得分:1)
这将计算表中的注释并选择最后输入的注释,然后仅当收到的计数低于表中注释的计数时才将它们作为json
数据传递给ajax:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
答案 2 :(得分:-1)
SELECT * FROM conversations order by insert_date desc limit 10
insert_date插入日期时间注释,我希望你有一个用于存储的字段,如果不立即添加它