AJAX Jquery 刷新所有内容,但我只想要新内容
我可能是在重新发明轮子,但这是故意的。我正在尝试使用 PHP HTML MySQL CSS 制作一个实时聊天应用程序。它在网络上运行得很好,每秒都会获取新内容。在 IE 中,你可以注意到每秒都会闪烁,似乎它一次又一次地提取所有数据,即使没有新内容,我不喜欢这样。
这是我的刷新 JS 代码:
$(document).ready(function() {
$("#data").load("data.php");
var refreshId = setInterval(function() {
$("#data").load('data.php');
}, 1000);
$.ajaxSetup({ cache: false });
});
data.php 只是一段时间循环遍历所有数据库记录并显示它们:
while ($row = mysql_fetch_array($result))
{
echo "<p><b>". $poster ."</b>: ". $message ."<br /><span style='font-size: 10px;'>". date('D d M - g:i:s a', strtotime($row['when'])) ."</span></p>";
}
我在互联网上寻找解决方案,褪色等,我不知道如何实现这一点,肯定有一些好的、简单且有效的方法吗?
I may be reinventing the wheel but that's intentional. I am trying to make a real-time chat application using PHP HTML MySQL CSS. It's working quite well over the network and grabbing new content every second. In IE you can notice a flicker every second, seemingly it is pulling all that data again and again, even if there's no new content, and I don't like that.
Here is my refresh JS code:
$(document).ready(function() {
$("#data").load("data.php");
var refreshId = setInterval(function() {
$("#data").load('data.php');
}, 1000);
$.ajaxSetup({ cache: false });
});
data.php is just a while looping through all the database records and showing them:
while ($row = mysql_fetch_array($result))
{
echo "<p><b>". $poster ."</b>: ". $message ."<br /><span style='font-size: 10px;'>". date('D d M - g:i:s a', strtotime($row['when'])) ."</span></p>";
}
I've looked and looked on the internet for solutions, fading etc, I can't think of how to accomplish this, surely there is some nice and easy and efficient way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将上次更新的时间戳传递给服务器并仅检索新内容。
You should pass a time stamp to the server of the last update and only retrieve new content.
我个人在喊箱中使用的最佳解决方案是使用全局变量在加载的数据中设置一个变量。
示例:
然后当您调用 data.php 时,您可以使用这个新参数来调用它。
你的 global_var 可以是任何东西,从最后插入的ID,或者最后的时间戳,或者???
The best solution, that I personally use in my shoutboxes, is to set a variable in the loaded data with a global variable.
Example:
Then when you call data.php you can call it with this new parameter.
Your global_var can be anything, from last inserted ID, or last timestamp, or???
这就是您所需要的,您只需根据需要修改它:
仅当新内容添加到数据库时才刷新 div 的内容
这将传递页面加载时的时间,并且仅当新内容添加时才会刷新数据已添加,请参阅第一个答案。
一切顺利 ;)。
This one is what you need, you only have to modify it for your needs:
Refresh a div's content only if new content is added to the database
This will pass the time when the page was loaded, and will refresh the data only if new content has been added, see the first answer.
All the best ;).