jquery ajax:以正确的顺序处理typeahead事件?

Rop*_*Rop 5 javascript ajax jquery typeahead

我正在使用html + jquery和java rest-service后端进行webapp.我有一个带有预先输入建议的文本字段,因此用户在字段中键入的每个字符都将触发服务器往返并更新预先建议列表.

代码的基本部分:

    var showTypeaheadSuggestions = function(data) {
        // update ui-element ...
    }

    var displayFailure = function() {
        // update ui-element ...
    }

    var searchText = $("#searchText");
    var searchTextKeyup = function() {
        var txt = searchText.val();
        $.ajax({
            url : typeaheadUrl(txt),
            type : 'GET',
            dataType : 'json',
        }).done(showTypeaheadSuggestions).fail(displayFailure);
    }
    searchText.on('keyup', searchTextKeyup);
Run Code Online (Sandbox Code Playgroud)

它基本上是有效的.但我正在考虑如果你打字会发生什么,例如,2个字母"ab"(这将首先触发"a"的请求,然后是"ab"的请求)...

然后,如果"a"响应需要更长的时间来处理,并 "ab"响应之后到达,会发生什么?我是否需要在我的代码中检测到这一点,丢掉"a"响应?

http://api.jquery.com/jquery.ajax/中它确实说:

承诺回调 - .done(),. find(),.byways()和.then() - 按照它们的注册顺序被调用.

这究竟是什么意思? 我希望这意味着$ .ajax()会自动处理上述情况.

但是,当我做一个小测试(在服务器端,我只是注入了2秒睡眠延迟,只有当搜索字符串完全"A"),事实证明它并没有如我所料的行为.

预先输入列表将首先使用"ab"响应进行更新,然后当"a"响应到达时,它也会更新,因此预先输入列表会得到错误的建议.

正确处理此问题的既定方法是什么?

Iva*_*eno 1

如果您想保持服务器端代码不变,还有另一种方法。您实际上可以将返回函数包装在一个类中,并为每个请求创建实例,然后将最新实例存储在全局范围变量中,并检查被调用方法的所有者是否与最新实例匹配:

var lastRequest;
var searchText = $("#searchText");

function requestClass()
{
    var that = this;

    this.showTypeaheadSuggestions = function(data) {
        //Update ui-element
        if (lastRequest == that)
            console.log('suggestions retrieved: ' + data);
        else
            console.log('this response (' + data + ') is ignored');
    };

    this.displayFailure = function() {
        //Update ui-element
        console.log('failure');
    };
}

var searchTextKeyup = function() {
    var request = new requestClass();
    lastRequest = request;

    var txt = searchText.val();
    $.ajax({
        url : typeaheadUrl(txt),
        type : 'GET',
        dataType : 'json',
    }).done(request.showTypeaheadSuggestions).fail(request.displayFailure);
}

searchText.on('keyup', searchTextKeyup);
Run Code Online (Sandbox Code Playgroud)

我已经用您在问题中提出的小测试对此进行了测试(当搜索字符串与“a”字符匹配时添加 2 秒延迟),结果如下:

suggestions retrieved: ab
this response (a) is ignored
Run Code Online (Sandbox Code Playgroud)