像这个 jquery 代码,我应该如何延迟 ajax 请求?输入是一个文本字段......在我头上......谢谢帮助......
var proname = "" ;
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}) ;
最佳答案
您想使用setTimeout
。
从您的使用情况来看,每次发生另一个 keyup 事件时都清除超时似乎是个好主意,以避免排队。
var requestDelay;
var proname;
$('input[name=proname]').keyup(function() {
if(e.which == 13 || $(this).val() == proname)
return;
proname = $(this).val();
// postpone the submit another 300 ms upon every new character
window.clearTimeout(requestDelay);
requestDelay = window.setTimeout(function() {
$.ajax(...);
}, 300);
});
关于javascript - 我应该如何延迟ajax请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992298/