3

I am trying to set up a comment system, in which when the users sends the comment it is displayed on their screen as if it were already stored on the database. My question is: what would happen if the users send comments and then navigate away (or most specifically close the window immediately) or they lose connection after the ajax post?

On the code side I have ajax({})...

Then I have code that takes the user input from the textarea and adds it to a div.

This means that the user gets to see the comment they entered instantaneously. But I would like to be sure if the server will get the post info even if the connection was lost, window was closed or the user navigated away.


More info for the question:

A user sends a post to the server with 1mb of values, then right after one millisecond he/she clicked on the button that made the post the browser window was closed.

Does the server receive and parse the response with ignore_user_abort(true); inside the file; was the post info received?

Any difference if it were get instead of post for this case?

Assume website.com?myget=value

Trying to connect then closing the window immediately, on a browser window for example, just hitting that on the address bar and then closing very right away, imagine it to be automatically.

step 1 go to website.com?myget=value (don't wait at all for any server response, just straight away (a millisecond or whatever it takes the script to do so) close completely the window.

Would $_GET['myget'] be received server side at index.php of website.com?

4

3 回答 3

1

将添加我的五美分。和ajax({})您将要求浏览器开始与您的服务器通信。它需要一些时间来建立连接(ping 时间)并将数据发送到服务器。这两部分都需要一些时间才能完成。为了让 PHP 开始执行,浏览器必须发送它必须发送的所有数据。无论是 POST 还是 GET。如果用户将中断发送过程(浏览器崩溃,标签关闭,计算机关闭)PHP 甚至不会启动。例如,您可以尝试发送一些大文件并使用调试器查看 PHP 脚本何时启动 - 仅在文件完全交付后(您甚至可以在文件上传之前关闭浏览器并查看您的脚本是否已执行) . 仅在将所有数据传递到服务器后才开始执行 PHP 并忽略在数据传递之前断开的连接是有意义的。否则可能会出现数据损坏的问题。没有人想要那样。另外,假设 PHP 是在所有内容交付到服务器之前启动的:您永远无法确定$_POST["something"]不可用,因为用户从未输入过它,或者它的数据尚未交付。

如果您使用常规表单提交或 XMLHTTPRequest,则没有区别。在这两种情况下,浏览器都需要一些时间来建立与服务器的连接并将数据传递给它。

于 2012-12-24T17:24:47.780 回答
1

这是一个用户体验问题,而不是技术问题。您要做的是仅在存储新评论后才显示新评论。工作流程应该是这样的:

  1. 用户类型消息
  2. 用户点击“提交”按钮
  3. 系统灰显“提交”按钮并显示一条消息,内容为“正在发布...”
  4. 当系统可以确认消息已成功存储时,系统将删除“正在发布...”文本并显示实际的新消息。

这样,用户就知道在请求完成之前不要关闭浏览器或导航离开。


或者,您可以onbeforeunload警告您的用户在关闭浏览器或导航之前等待。工作流程类似于:

先决条件:您在某处有一个持久计数器(cookie、本地存储、隐藏字段等)。当页面加载时,它从0开始。

  1. 用户类型消息
  2. 用户点击“提交”按钮
  3. 发送 AJAX 请求
  4. 计数器增加1
  5. 请求完成,您得到响应(无论成功与否 - 错误处理是另一个问题),将计数器减1

如果在任何时候unload触发了事件,系统将检查计数器。如果大于0,则警告用户他们的请求尚未完成并且他们可能会丢失他们的评论 (a-la-Gmail)。

于 2012-12-24T16:43:51.293 回答
0

在大多数情况下,您对服务器执行的任何操作都将继续执行,直到服务器上运行的 PHP 尝试将结果输出回浏览器。只有在这一点上,PHP 才会检查连接是否仍然存在,并根据用户中止设置做任何应该做的事情。因此,例如,如果您想接收帖子、更新数据库条目,然后回显某种成功消息,那么只要您在查询数据库之前没有进行任何输出,数据库活动就应该继续。

POST 与 GET 在这种行为上没有区别。

于 2012-12-24T16:36:25.497 回答