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

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

在这里使用jQuery !


当前回答

它只是一行下划线。js debounce函数:

$('#my-input-box').keyup(_.debounce(doSomething , 500));

这基本上是在我停止输入500毫秒后做某事。

欲了解更多信息:http://underscorejs.org/#debounce

其他回答

const inText = document.getElementById('inText') const outText = document.getElementById('outText') Const delay = 1000 让计时器 inText。addEventListener('input', code => { clearTimeout(计时器); timer = setTimeout(x => { outText。innerHTML = inText.value },延迟,代码) }) <textarea id='inText'>编辑这个和 <pre id='outText'>在你停止输入一秒钟后看到结果</pre>

它只是一行下划线。js debounce函数:

$('#my-input-box').keyup(_.debounce(doSomething , 500));

这基本上是在我停止输入500毫秒后做某事。

欲了解更多信息:http://underscorejs.org/#debounce

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

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));

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

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

我在我的清单中实现搜索,需要它是基于ajax的。这意味着在每次键更改时,都应该更新并显示搜索结果。这会导致大量的ajax调用发送到服务器,这不是一件好事。

经过一些工作,我提出了一种在用户停止输入时ping服务器的方法。

这个解决方案对我很有效:

$(document).ready(function() {
    $('#yourtextfield').keyup(function() {
        s = $('#yourtextfield').val();
        setTimeout(function() { 
            if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
                $.ajax({
                    type: "POST",
                    url: "yoururl",
                    data: 'search=' + s,
                    cache: false,
                    beforeSend: function() {
                       // loading image
                    },
                    success: function(data) {
                        // Your response will come here
                    }
                })
            }
        }, 1000); // 1 sec delay to check.
    }); // End of  keyup function
}); // End of document.ready

您将注意到,在实现此操作时不需要使用任何计时器。