我有一个文本框,每个用户输入字母时为我做同一个Ajax请求搜索并显示结果活的用户。通常当用户键入花费要比为用户输入新的信提出的要求较长时间的字母,因此新的请求是第一个已结束之前完成。这将是好得多,如果第一个可能结束之前,我做了一个请求。有没有好的办法只能使一个新的请求,如果最新的请求已经结束了?
这是我的jQuery code:
$(#MyTextBox)。改变(函数(){
如果(this.value.length→2){
$阿贾克斯({
键入:GET,
网址:http://www.domain.com/Service.svc/Search?keyword=+ THIS.VALUE,
数据类型:JSON,
成功:功能(数据){
//这里我有一些code,显示结果为用户
}
});
}
});
解决方案
您可以创建一个布尔值,将举行true或false取决于是否有已经发生的请求。它设置为true,当你启动一个请求,并将其设置为false在回调函数。
VAR request_in_process = FALSE;
$(#MyTextBox)。改变(函数(){
如果(this.value.length→2&安培;&安培;!request_in_process){
request_in_process = TRUE;
$阿贾克斯({
键入:GET,
网址:http://www.domain.com/Service.svc/Search?keyword=+ THIS.VALUE,
数据类型:JSON,
成功:功能(数据){
request_in_process = FALSE;
//这里我有一些code,显示结果为用户
}
});
}
});
I have a textbox that for each time a user inputs a letter I make a search with an ajax request and show the result "live" for the user. Often when a user types the letters it takes longer time for the request to be made than for the user to input a new letter, hence a new request is made before the first one have ended. It would be much better if the first one could end before I do the next request. Is there a good way to only make a new request if the latest request have ended?
This is my jquery code:
$("#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
}
});
}
});
解决方案
You could create a boolean that will hold true or false depending on if there is a request already happening. Set it to true when you start a request and set it back to false in your callback function.
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
}
});
}
});
相关推荐
最新文章