dongyao2022 2019-07-28 21:44
浏览 152

jQuery POST在处理用户与锚点的交互之前等待响应

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)?
  • 写回答

1条回答 默认 最新

  • duanji9311 2019-07-28 22:18
    关注

    Where is the problem?

    The issue at hand is how you manage interactions independently of the request. If you don't want someone to click a link before a request has been fulfilled, then you should manage that until it does.

    For example, declare a flag in your code that determines whether or not your request has been resolved. Defaults to false. Then run your ajax query. Upon success, it will set requestComplete to true.

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

    Bind a listener to your link(s) that only allows interaction if the flag is true. The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links this would be following the link.

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

    And so your markup will look something like this:

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

    To demonstrate the blocking of a browsers default behaviour, explore this fiddle.

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?