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

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

在这里使用jQuery !


当前回答

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

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

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

其他回答

是的,你可以在每个key up事件上设置一个超时,比如2秒,它会触发一个ajax请求。您还可以存储XHR方法,并在随后的按键事件中中止它,这样可以节省更多的带宽。下面是我为自己的自动完成脚本写的一些东西。

var timer;
var x;

$(".some-input").keyup(function () {
    if (x) { x.abort() } // If there is an existing XHR, abort it.
    clearTimeout(timer); // Clear the timer so we don't end up with dupes.
    timer = setTimeout(function() { // assign timer a new timeout 
        x = $.getJSON(...); // run ajax request and store in x variable (so we can cancel)
    }, 2000); // 2000ms delay, tweak for faster/slower
});

希望这能有所帮助,

马可

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

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

嗯,严格来说不是,因为计算机无法猜测用户何时完成输入。当然,你可以在按下键时触发计时器,并在每次按下键时重置它。如果计时器过期,用户在计时器持续时间内还没有输入-你可以称之为“完成输入”。

如果您希望用户在输入时暂停,则无法知道他们何时完成。

(当然,除非你能从数据中判断他们何时完成)

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

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));
var timer;
var timeout = 1000;

$('#in').keyup(function(){
    clearTimeout(timer);
    if ($('#in').val) {
        timer = setTimeout(function(){
            //do stuff here e.g ajax call etc....
             var v = $("#in").val();
             $("#out").html(v);
        }, timeout);
    }
});

完整的例子:http://jsfiddle.net/ZYXp4/8/