Jquery UI Autocomplete Shows Response for Earlier Text

一笑奈何 提交于 2020-01-12 05:55:43

问题


I'm using Jquery autocomplete. If a user types 2 characters then waits, then types another. If the first response comes after the second, it will briefly show the second list then show the first list. How can I cancel the first request after a user starts typing more?

    $("#city").autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "/geo/json_autocomplete.php",
                dataType: "json",
                data: {
                    term: $("#city").val(),
                    countryid: $("#countryid").val()
                },
                success: function( data ) {
                    response( $.map( data, function( item ) {
                        //console.debug(item.value+" "+item.label+" "+item.id);
                        return {
                            label: item.label,
                            value: item.value,
                            id: item.id
                        }
                    }));
                }
            });
        },
        minLength: 2,
        delay: 500,
        select: function( event, ui ) {
            $("#cityid").val(ui.item.id);
            showForm();
        }
    });

回答1:


You could try storing the xhr in a variable and comparing it with the xhr parameter you get in the AJAX success callback. Only call the response function if the two match. You can also adjust the "delay" parameter accordingly.

var lastXhr;

$("#city").autocomplete({
    delay: 500, // 500ms between requests.
    source: function( request, response ) {
        lastXhr = $.ajax({
            url: "/geo/json_autocomplete.php",
            dataType: "json",
            data: {
                term: $("#city").val(),
                countryid: $("#countryid").val()
            },
            success: function( data, status, xhr ) { 
                if (xhr === lastXhr) {
                     response( $.map( data, function( item ) {
                    //console.debug(item.value+" "+item.label+" "+item.id);
                        return {
                            label: item.label,
                            value: item.value,
                            id: item.id
                        };
                    }));
                }
            }
        });
    },
    minLength: 2,
    delay: 500,
    select: function( event, ui ) {
        $("#cityid").val(ui.item.id);
        showForm();
    }
});


来源:https://stackoverflow.com/questions/9040929/jquery-ui-autocomplete-shows-response-for-earlier-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!