当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。

是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?

在这里使用jQuery !


当前回答

一旦你检测到文本框的焦点,在键上做一个超时检查,并重置它每次触发。

当超时结束时,执行ajax请求。

其他回答

不是一个直接的答案,但如果有人在寻找AngularJS的解决方案。我根据这里流行的解决方案写了一个指令。

 app.directive("ngTypeEnds", ["$timeout", function ($timeout) {
    return function (scope, element, attrs) {
        var typingTimer;               
        element.bind("keyup", function (event) {
            if (typingTimer)
                $timeout.cancel(typingTimer);
            if (angular.element(element)[0].value) {
                typingTimer = $timeout(function () {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngTypeEnds);
                    });
                }, 500);
            }
            event.preventDefault();
        });
    };
}]);

对于alpine.js用户<input @input.debounce.500ms="fn()" >

我需要为特定的控制运行我的程序,这对我来说很有效:

function debounce(func, timeout) {
            let timer;
            return (...args) => {
                clearTimeout(timer);
                timer = setTimeout(() => { func.apply(this, args); }, timeout);
            };
        }

$('#txtFilterClientCode').keyup(debounce(function () {
            console.log("Test");
        }, 1000));

下面是一个解决方案,它在不输入1秒后触发,但在输入为空白时也会立即触发。这在用户删除输入查询后清除搜索结果时非常有用。此解决方案还支持复制和粘贴到搜索框中。$(() =>{…});在简单的Jquery术语中,包装代码的顶部部分仅仅意味着“在页面加载时执行此操作”。

var searchTimer;
var searchInterval = 1000;

$(() => {
    $('#search-box').on('input', (event) => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            searchContacts(event.target.value);
        }, (event.target.value.length > 0) ? searchInterval : 0);
    });
});

function searchContacts(val) {
    console.log('searching: ' + val);
}

前两个答案都不适合我。所以,这是我的解决方案:

var timeout = null;

$('#myInput').keyup(function() {
    clearTimeout(timeout);

    timeout = setTimeout(function() {
        //do stuff here
    }, 500);
});