获取新的MySQL条目并动态附加到现有div

我有一个PHP脚本来选择数据库中的注释记录,然后将它们打印到页面上。 我想要发生的是,如果用户在页面上,而另一个用户对所述页面上的项目发表评论,它会自动将新评论附加到底部。 我遇到的问题是我不知道如何区分所有状态。

我生成状态注释的代码是:

= 2) { ?>   <div id="commentbox" class="" style="padding:5px 5px 5px 5px;"> 
<img src="https://stackoverflow.com/questions/11229645/fetch-new-mysql-entries-and-append-to-existing-divs-dynamically/" width="36px" style=" display:inline; position:relative;"/>
<a href="https://stackoverflow.com/questions/11229645/fetch-new-mysql-entries-and-append-to-existing-divs-dynamically/profile.php?uid=" style="position:relative; font-size:13px; margin-left:10px; font-family:Arial; color:#3a3a3a; text-decoration:none;"> <p class="" style="position:relative; margin-left:5px;">

TL:DR; 如何在不刷新页面的情况下自动获取新注释并将其附加到上述脚本中生成的注释中。

JQUERY

 $(document).ready(function(){ var lastcheck=''; setInterval(function() { $.ajax({ url: 'URL_TO_PHP_SCRIPT', type: 'POST', data: {'lastcheck':lastcheck}, success: function(result){ if (result!='nothing_new'){ lastcheck=result.lastcheck /*Update lastcheck*/ var data=result.data; $.each(data, function(i,val){ //Foreach comment you do what you need, like append, prepend, etc. data[i]."key" to get the value. }); } } }); }, 15000 /* This will check each 15 seconds, you can change it */); }); 

PHP SIDE

  $lastcheck=$_POST['lastcheck']; /* You should add a date field to each new created comment,then filter by "orderby date > $lastcheck" so you get comments since your last check You get the new comments here ... ... .. */ if (!empty($arrayofnewcomments)){ /*The output*/ echo json_encode(array('lastcheck'=>date('Ymd H:i:s'),'data'=>$arrayofnewcomments)); }else{/*No new comments*/ echo 'nothing_new'; } 

这是我提出的一些代码,这是一个一般的想法,但它的工作原理。 它将每15秒检查一次新评论。