javascript - 在 jquery 中如何防止多个帖子同时发布到同一页面?

标签 javascript jquery

我有一个像这样的输入搜索:

<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/

相关文章:

javascript - 导航栏在 Bootstrap 中不起作用 : 4. 0.0-beta.2

php - 具有多个父项的 Javascript/PHP 家谱生成器

javascript - jquery ui datepicker 像输入小部件

javascript - JS : how to listen event after template contruction?

javascript - 将矩阵输出文本更改为西里尔文 unicode 脚本

javascript - 防止浏览器加载拖放文件

php - 设计用户界面时有趣的计算内容

javascript - 如何使用 Css 动态更改背景颜色

javascript - 如何从 JavaScript 中的字符串中删除双引号

javascript - jquery 点击链接?