我有一个文本框,每次用户输入一个字母时,我都会使用 ajax 请求进行搜索,并为用户“实时”显示结果。通常,当用户键入字母时,发出请求所需的时间比用户输入新字母所需的时间更长,因此在第一个请求结束之前发出新请求。如果第一个请求能够在我执行下一个请求之前结束,那就更好了。有没有一种好方法,仅在最新请求结束后才发出新请求?
这是我的 jquery 代码:
$("#MyTextBox").change(function() {
if (this.value.length > 2) {
$.ajax({
type: "GET",
url: "http://www.domain.com/Service.svc/Search?keyword=" + this.value,
dataType: "json",
success: function(data) {
//here I have some code that shows the result for the user
}
});
}
});
您可以创建一个布尔值,该值将根据是否已发生请求而保持 true 或 false。当您启动请求时将其设置为 true,并在回调函数中将其设置回 false。
var request_in_process = false;
$("#MyTextBox").change(function() {
if (this.value.length > 2 && !request_in_process) {
request_in_process = true;
$.ajax({
type: "GET",
url: "http://www.domain.com/Service.svc/Search?keyword=" + this.value,
dataType: "json",
success: function(data) {
request_in_process = false;
//here I have some code that shows the result for the user
}
});
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)