我很好奇facebook是如何实时显示内容的。例如,当一个用户发表评论时,来自世界其他地方的另一个人可以看到该评论紧跟在该用户评论之后。
我知道ajax/jquery可以在不刷新页面的情况下执行.append(数据),但这不会在其他用户上显示出来。会吗?
发布于 2011-10-01 10:33:39
我不确定Facebook是如何做到这一点的,但以下是它可能的工作原理。
编辑:
深入了解你应该使用什么函数。首先,你有一个评论列表。
<ul id="comments" style="list-style-type: none;">
</ul>我将list-style-type设置为none,这样项目符号就不会显示。
当页面加载时,使用jquery AJAX函数来执行对提供评论的页面的HTTP GET请求。然后将它们注入到DOM中,使用
$('#comments').html(loadedAJAXData);其中loadedAJAXData是您从GET请求中获得的数据。
所以注入的数据看起来像这样-
<li>Comment 1
<li>Comment 2
<li>Foo现在评论列表看起来像这样-
<ul id="comments" style="list-style-type: none;">
<li>Comment 1
<li>Comment 2
<li>Foo
</ul>现在你有你的评论了。有人发表了新的评论吗?它被发送到您的网站,这将在数据库中插入一个新的评论行。
假设您有另一个页面,您从该页面请求评论的数量。让我们称其为comments.php?count。
// set interval
var tid = setInterval(getCommentsCount, 2000);
function getCommentsCount() {
//AJAX will request comment count from comments.php?count .
//Comment count is stored in the variable newCommentCount. Previous or cached comment //count is stored in oldCommentCount.
if(oldCommentCount != newCommentCount){ //If we have a different number of comments
for(int i = oldCommentCount;i<newCommentCount;i++){
//For each new comment
//Make a request to comments.php?get=commentOffset
//Then inject it into the DOM using
$('#comments').append(comment);
oldCommentCount++;
}
}
// no need to recall the function (it's an interval, it'll loop forever)
}例如,在此脚本中,浏览器每2秒请求一次注释计数。我们的oldCommmentCount是0。我们的newCommentCount是2。对于每个新的评论,我们都会向comments.php?get=commentOffset发出一个请求。其中commentOffset是i。请求新注释时,我们获取它的数据,将其附加到注释列表中,然后递增oldCommentCount。
发布于 2011-10-01 16:21:21
尝试如下所示:
function checkServer() {
$.ajax('http://example.com/check', {data: ''}, function(data) {
// Process data changes here
}, 'json');
}
$(document).ready(function() {
setInterval("checkServer()", 500)
});发布于 2011-10-01 10:32:39
这是一个调用到服务器的ajax,服务器查询数据库并返回任何新的注释,因为查询命中数据库,所以任何用户写入表中的任何新注释都将被返回。
https://stackoverflow.com/questions/7617779
复制相似问题