Ajax 聊天 - 仅在发生更改时更新

发布于 2024-09-05 17:12:54 字数 526 浏览 9 评论 0原文

我目前有一个基于 Ajax 的聊天,我试图通过仅在发生更新时加载聊天脚本来简化聊天。因此,如果数据库中没有任何更改,则不需要继续加载任何内容。

我当前的逻辑是:

  • JavaScript 函数每 1/2 秒触发一次以获取聊天日志 (setInterval())

如果没有任何变化,那么继续调用它似乎相当低效。相反,我想做的是:

  1. JavaScript 函数检查数据库中是否有任何日志
  2. 如果是 - 加载新日志,如果否 - 保留当前显示的日志。

但我该怎么办呢?我当前使用的功能是:

function updateShouts() {
    $('#chatArea').load('chat.php'); // load chat logs
}
setInterval("updateShouts()", 500);  // call function every half a second

I currently have an Ajax-based chat, which I am trying to streamline by only loading the chat script when an update occurs. Thus, nothing needs to keep loading if nothing has changed in the database.

My current logic says:

  • JavaScript function fires every 1/2 second to get chat logs (setInterval())

If nothing has changed, though, it seems fairly inefficient to keep calling it. Instead, what I'd like to do is:

  1. JavaScript function checks if there are any new logs in the database
  2. If YES - load the new logs, if NO - leave the currently displayed logs alone.

How would I go about this, though? The function I am currently using is:

function updateShouts() {
    $('#chatArea').load('chat.php'); // load chat logs
}
setInterval("updateShouts()", 500);  // call function every half a second

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

故人的歌 2024-09-12 17:12:54

我会将timestamp(或message_id)与服务器端脚本发送到客户端的任何聊天消息一起传递。然后客户端只需请求新消息,服务器仅发送新消息。

因此,假设每条聊天消息都有一个 ID。我将 chat.php 设计为接受如下参数:

chat.php?since=12345

12345 将是客户端看到的最后一条消息的 idchat.php 本质上做了类似的事情:

SELECT * FROM chatmessages WHERE id > $since

...并传回一个漂亮的小数据结构(比如说,以 JSON 编码的对象数组)。

因此,如果没有新的聊天消息,服务器只是传回一个空数组。

我不认为你能比这更有效率。

编辑:

我意识到这样做需要更多的客户端编码。您不再只是用整个聊天历史记录来更新某个 div。您还需要在 ajax 调用上有一个处理程序,用于迭代结果,并且对于每条消息,以编程方式为该行构造一个 div,然后将其附加到您的聊天 div< /代码>。

I would pass timestamps (or message_ids) along with any chat messages that the server-side script sends to a client. Then the client simply asks for new messages, and the server sends only what's new.

So, imagine that each chat message has an ID. I'd design my chat.php to accept a parameter like so:

chat.php?since=12345

12345 would be the id of the last message the client has seen. chat.php essentially does something like:

SELECT * FROM chatmessages WHERE id > $since

... and passes back a nice little data structure (an array of objects, encoded in JSON, let's say).

So, if there are no new chat messages, the server is just passing back an empty array.

I don't think you can be any more efficient than that.

EDIT:

I realize that doing it this way requires a little more client-side coding. You're no longer just updating some div with the whole chat history. You'll also need to have a handler on your ajax call that iterates over the results, and for each message, programatically construct a div for that line, then appends it to your chat div.

梦晓ヶ微光ヅ倾城 2024-09-12 17:12:54

一种相对简单的方法是使用 AJAX 获取一个页面,该页面仅告诉您是否有任何更新。例如,您可以获取像 checkForUpdate.php 这样的页面,其中包含 1 或 0 来指示聊天中是否有任何新内容。如果您得到 1,您可以继续加载完整的 chat.php 页面。

(如果您以前没有使用过 AJAX,这是一个非常好的教程:http://www.tizag。 com/ajaxTutorial/

另一种解决方案(我认为可能更好)是加载一个仅包含最新聊天行的页面。例如,假设您当前正在显示聊天的第 1-14 行。然后,您可以使用 AJAX 获取 getLines.php?s=14 等内容。此页面仅显示第 14 行之后的聊天行。然后您只需将这些行附加到当前聊天窗口的末尾即可。

One relatively simple way to do this is to use AJAX to fetch a page that simply tells you if there has been any update. So for example, you could fetch a page like checkForUpdate.php that has a 1 or a 0 to indicate if there is anything new in the chat. If you got a 1 back, you could go ahead and load the full chat.php page.

(If you haven't used AJAX before, this is a pretty good tutorial: http://www.tizag.com/ajaxTutorial/)

Another solution (and one that I think is probably better) is to load a page that only has the most recent chat lines. For example, say you are currently displaying lines 1-14 of the chat. You could then use AJAX to fetch the content of, for example, getLines.php?s=14. This page would only display the lines of the chat after line 14. You would then just append those lines to the end of the current chat window.

不必在意 2024-09-12 17:12:54

如您所知,.load 函数使用 chat.php 文件返回的输出填充元素。这个 .load 函数执行两个步骤:它向 chat.php 发出 ajax 请求,然后将元素的值设置为 chat.php 的输出。你想做的只是第一步。为此,请使用 .ajax 函数

http://api.jquery.com/jQuery.ajax/< /a>

我建议不要使用 chat.php 文件,而是调用不同的脚本,例如 isChatUpdated.php。该脚本将按照名称所示执行操作,并检查聊天中是否有任何更改。然后,您可以使用该结果来确定是否需要调用 .load 函数。

As you know the .load function fills an element with the output returned by your chat.php file. This .load function does two steps: It makes an ajax request to the chat.php and then sets the value of the element to the output of chat.php. What you want to do is just the first step. To do this use the .ajax function

http://api.jquery.com/jQuery.ajax/

Instead of using the chat.php file I would suggest calling a different script like isChatUpdated.php. That script will do just like the name suggests and check if there has been any changes in the chat. You can then use that result to figure out whether you need to call your .load function.

做个少女永远怀春 2024-09-12 17:12:54

无论哪种方式,您都需要在服务器端查询数据库,因此如果它返回日志数据或单个值,则几乎无关紧要。
您可以根据返回值决定不更新#chatArea,但您必须再次调用来检索日志,否则。

Either way you need to query the db in the server side, so is almost irrelevant if it returns log data or a single value.
You can decide not to update #chatArea, based on a return value, but you have to make another call to retrieve the logs, otherwise.

似梦非梦 2024-09-12 17:12:54

我首先会创建一个名为 messages.php 的文件,看起来像这样:

<?php header('Content-Type: application/json');

$messages_since = !empty($_POST['since']) 
    ? mysql_real_escape($_POST['since']) 
    : '0000-00-00 00:00:00');

// Get all messages from database since the $messages_since date_time

echo json_encode($array_with_messages);

然后在客户端使用 jQuery 或类似的东西,我会做这样的事情:

  1. 使用类似 $.post('messages) 的东西获取消息.php', new_messages_handler)
  2. 在处理程序中,我将为我们返回的每条新消息创建 html,并将其附加/添加到聊天容器中,并存储最新消息的创建时间。
  3. 稍等一下,
  4. 使用诸如 $.post('messages.php', {since:latest_datetime_we_have}, new_messages_handler) 之类的内容获取新消息
  5. 转到 2

至少它在我的脑海中运行得很好 :p

I would first create a file called for example messages.php that looked something like this:

<?php header('Content-Type: application/json');

$messages_since = !empty($_POST['since']) 
    ? mysql_real_escape($_POST['since']) 
    : '0000-00-00 00:00:00');

// Get all messages from database since the $messages_since date_time

echo json_encode($array_with_messages);

Then on the client side using jQuery or something like that I would do something like this:

  1. Get messages using something like $.post('messages.php', new_messages_handler)
  2. In the handler I would create html for each new message we got back and append/prepend it to the chat container as well as store what time the latest message was created.
  3. Wait a while
  4. Get new messages using something like $.post('messages.php', {since: latest_datetime_we_have}, new_messages_handler)
  5. Go to 2

At least it works pretty nicely in my head :p

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文