自动完成改进

时间:2015-10-02 18:34:25

标签: javascript jquery web-services autocomplete jquery-autocomplete

我想为Textbox Autocomplete实现一项功能。目前我使用jQuery Autocomplete,但我无法实现与搜索延迟相关的功能;例如,如果我搜索“新”,我将有一个自动完成列表,其中包含['New York','New South Memphis'..... 现在,如果我按“S”并立即按下箭头,那么我最终会选择第一个项目,即“纽约”而不是获得以“新S”开头的城市的结果。 [以“新S”开头的搜索城市的Web服务调用被触发] 我想要实现的是阻止向下箭头直到检索结果。如果有人能够解释我应该关注什么来实现这个功能,或者由于Web服务调用的异步特性而无法解决?

$(document).ready(function() {

    $("#locations").keydown(function() {

        var keyword = $("#locations").val();
        var url = 'http://autocomplete.wunderground.com/aq?format=json&cb=myCallbackFn&query=' + keyword;
        $.ajax({
            type: 'GET',
            url: url,
            async: true,
            dataType: 'jsonp',
            error: function(e) {
                console.log(e.message);
            }
        });
    });



});

var myCallbackFn = function(data) {
    var cities = [];
    for (i = 0; i < data.RESULTS.length; i++) {
        if (data.RESULTS[i].type == 'city') {
            cities.push(data.RESULTS[i].name);
        }
    }

    $("#locations").autocomplete({
        source: cities
    }).autocomplete("widget").addClass("fixed-height");
}
<html>
	<head>
		<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css">
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
		<script type="text/javascript" src="custom.js"></script>
		
		<style>
				.fixed-height {
					padding: 1px;
					max-height: 200px;
					overflow: auto;
				}
		</style>
	</head>
	<body>
			<div class="ui-widget">
						<label for="tags">Autocomplete: </label>
						<input id="locations" type="text" size="50"/>
	       </div>   
   </body>
</html>

1 个答案:

答案 0 :(得分:0)

完成此操作的一种方法是在触发建议的新GET请求时删除所有自动完成建议,或者设置一个标志以忽略向下箭头按键,直到请求解决。

相关问题