Jquery ajax请求,等待最新请求完成

Mar*_*tin 8 ajax jquery httpwebrequest

我有一个文本框,每次用户输入一个字母时,我都会使用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
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

dl.*_*dl. 10

您可以创建一个包含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
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)


cee*_*yoz 8

您可以中止AJAX请求.将请求作为变量跟踪,并在重新启动请求之前中止它.

var request = $.ajax({ ... });
request.abort();
Run Code Online (Sandbox Code Playgroud)

这具有对用户输入更敏感的附加优点.如果用户在启动第一个请求后输入了更多内容,他可能不再关心第一组结果了.中止并重新创建AJAX请求意味着用户可以获得更好的结果集.