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

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

在这里使用jQuery !


当前回答

我喜欢Surreal Dream的答案,但我发现我的“doneTyping”函数会在每次按键时触发,即如果你快速输入“Hello”;当您停止输入时,该函数将触发5次,而不是只触发一次。

问题是javascript的setTimeout函数似乎不会覆盖或杀死任何旧的超时设置,但如果你自己做它工作!因此,如果设置了typingTimer,我只是在setTimeout之前添加了一个clearTimeout调用。见下文:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example

//on keyup, start the countdown
$('#myInput').on("keyup", function(){
    if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#myInput').on("keydown", function(){
    clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

注意:我本来想把这句话作为对Surreal Dream的回答的评论,但我是一个新用户,没有足够的声誉。对不起!

其他回答

用于将参数与ES6语法一起传递给函数。

$(document).ready(() => {
    let timer = null;
     $('.classSelector').keydown(() => {
     clearTimeout(timer); 
     timer = setTimeout(() => foo('params'), 500);
  });
});

const foo = (params) => {
  console.log(`In foo ${params}`);
}

不是一个直接的答案,但如果有人在寻找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()" >

如果有必要让用户离开字段,我们可以使用“onBlur”而不是Javascript中的Onchange

  <TextField id="outlined-basic"  variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />

如果这是不必要的设置定时器将是一个很好的选择。

我在我的清单中实现搜索,需要它是基于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

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