php - 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.
- 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?)?
- Is it possible to solve this issue (and how)?
解决方案
问题出在哪里?
手头的问题是如何独立于请求管理交互。如果您不希望有人在请求完成之前点击链接,那么您应该管理它,直到它完成为止。
例如,在您的代码中声明一个标志,以确定您的请求是否已得到解决。默认为false
. 然后运行您的 ajax 查询。成功后,它将设置requestComplete
为true
。
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。
推荐阅读
- python - 如何在条件下将列名列表添加到熊猫中的DataFrame
- sql - 如何防止sql交叉连接中的重复行
- python - Python panda从另一个df中搜索df中的值
- javascript - 如何在多边形要素上叠加点要素
- docker - 直接运行时在 docker 容器中编译 cpp 文件失败,但如果使用交互式容器则可以
- c# - 我可以使用反射调用结构属性的“设置”方法吗?
- node.js - 当给定一个空白 index.js 文件时,为什么 ElectronJS 不会简单地退出?
- javascript - 当 img src 没有值时,更新 html 中的默认 img src
- python - pyspark:使用 window() 函数并比较字符串
- scala - 这是使用什么 scala 语言功能?它似乎从 JsObject 中提取值并转换它?