当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当前回答
是的,你可以在每个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
});
希望这能有所帮助,
马可
其他回答
这是我写的一个简单的JS代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
var date = new Date();
initial_time = date.getTime();
if (typeof setInverval_Variable == 'undefined') {
setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
}
}
function DelayedSubmission_Check() {
var date = new Date();
check_time = date.getTime();
var limit_ms=check_time-initial_time;
if (limit_ms > 800) { //Change value in milliseconds
alert("insert your function"); //Insert your function
clearInterval(setInverval_Variable);
delete setInverval_Variable;
}
}
</script>
</head>
<body>
<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />
</body>
</html>
用于将参数与ES6语法一起传递给函数。
$(document).ready(() => {
let timer = null;
$('.classSelector').keydown(() => {
clearTimeout(timer);
timer = setTimeout(() => foo('params'), 500);
});
});
const foo = (params) => {
console.log(`In foo ${params}`);
}
我需要为特定的控制运行我的程序,这对我来说很有效:
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));
如果您正在寻找特定的长度(例如邮政编码字段):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
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>