首页 > 解决方案 > jQuery POST waits for response before processing user interaction with anchors

问题描述

Let's say I have a simple jQuery POST script:

$(document).ready(function () {
    $.post("post-data.php")
        .done(function (data) {
            // Done function
        }).fail(function () {
            // Fail function
        });
});

Let's say I have this HTML:

<div id="page">
    <a href="link.php">Some link</a>
    <div id="jquery-data-response"></div>
</div>

If post-data.php returns data after 10 seconds and I click on "Some link" within 10 seconds, the page "link.php" is loaded after the jQuery POST request is completed, so the user has to wait for a maximum of 10 seconds.

This applies to jQuery GET requests as well.

Now I have two questions.

  1. Where is the problem? Is it a Server issue (let's assume that the script is fully optimized and can't be faster than 10 seconds, it happens on localhost with XAMPP too), a jQuery issue (a missing function that handles user-interactions?) or a browser issue (does Chrome have to wait before all requests are processed?)?
  2. Is it possible to solve this issue (and how)?

标签: phpjquerypost

解决方案


问题出在哪里?

手头的问题是如何独立于请求管理交互。如果您不希望有人在请求完成之前点击链接,那么您应该管理它,直到它完成为止。

例如,在您的代码中声明一个标志,以确定您的请求是否已得到解决。默认为false. 然后运行您的 ajax 查询。成功后,它将设置requestCompletetrue

let requestComplete = false;

$.post("post-data.php")
  .done(function (data) {
    // this will prompt your listener to allow native execution
    requestComplete = true;
  })
  .fail(function () { ... });

将侦听器绑定到仅在标志为 时才允许交互的链接true。事件处理程序的返回值决定了默认浏览器行为是否也应该发生。在单击链接的情况下,这将跟随链接。

$(document).on('click', '.link', function (event) {
  return requestComplete;
});

所以你的标记看起来像这样:

<div id="page">
  <a href="link.php" class="link">Some link</a>
  <div id="jquery-data-response"></div>
</div>

要演示阻止浏览器默认行为,请探索这个 fiddle


推荐阅读