我有一个像这样的输入搜索:
<input type="search" autocomplete="off" name="searchSchools" id="searchSchools" value="" onKeyUp="searchSchools(this.value)" />
正如您所见,每次触发 onKeyUp 事件时,我都会调用一个名为“searchSchools”的函数,在其中搜索与 PHP 中输入搜索的当前值匹配的学校,并以 JSON 格式返回它们,问题是,如果我快速输入多个请求被发送到 PHP 页面,我想阻止这种情况,只有当此函数没有向同一页面发出其他请求时,我才想将 post 请求发送到该页面。
这是函数:
function searchSchools(name){
$.post("search-schools.php", { name: name },
function(data) {
//-> Here i do whatever with data returned
},
"json"
);
}
最佳答案
在$.post
中添加延迟..尝试如下,
var timer = null, xhrReq = null;
function searchSchools(name){
if (timer != null) {
clearTimeout(timer);
}
timer = setTimeout(function () {
if(xhrReq != null) {
xhrReq.abort(); //to kill all prev request and take the latest
}
xhrReq = $.post("search-schools.php", { name: name },
function(data) {
//-> Here i do whatever with data returned
},
"json"
);
}, 1000); //will be posted only after 1 second.
}
编辑:添加了xhr.abort()
以中止任何旧请求并仅考虑最新的请求。
关于javascript - 在 jquery 中如何防止多个帖子同时发布到同一页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10690593/