jQueryUI中关于AutoComplete的说明

jQueryUI中关于AutoComplete的说明

本文只是对jQueryUI的AutoComplete插件官方文档的摘录,写的比较好的中文使用教程请参见下面的资料:

囧月 坐井观天 jQuery UI Autocomplete 体验 http://www.cnblogs.com/lwme/archive/2012/02/12/jquery-ui-autocomplete.html

 

 

什么是AutoComplete及使用场景

AutoComplete:文本框的自动填充控件AutoComplete,类似于Google搜索输入框提供的功能。为什么有这样的功能呢,因为用户都很懒

 

Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to enter previous selected values, for example you could use Autocomplete for entering tags, to complete an address, you could enter a city name and get the zip code, or maybe enter email addresses from an address book.

 

如果选项数据量很少,比如10条以内,个人觉得使用radio或者select更好。

 

AutoComplete使用样例(本地静态数据)

 

<meta charset="utf-8">
	
	<script>
	$(function() {
		var availableTags = [
			"ActionScript",
			"AppleScript",
			"Asp",
			"BASIC",
			"C",
			"C++",
			"Clojure",
			"COBOL",
			"ColdFusion",
			"Erlang",
			"Fortran",
			"Groovy",
			"Haskell",
			"Java",
			"JavaScript",
			"Lisp",
			"Perl",
			"PHP",
			"Python",
			"Ruby",
			"Scala",
			"Scheme"
		];
		$( "#tags" ).autocomplete({
			source: availableTags
		});
	});
	</script>


<div class="demo">

<div class="ui-widget">
	<label for="tags">Tags: </label>
	<input id="tags" />
</div>

</div><!-- End demo -->


 

 

选项数据的三种提供方式(本地数组、指定URL、Callback)

You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

  • an Array with local data
  • a String, specifying a URL
  • a Callback

期望数据格式(Expected data format)

The data from local data, a url or a callback can come in two variants:

  • An Array of Strings:
    [ "Choice1", "Choice2" ]
  • An Array of Objects with label and value properties:
    [ { label: "Choice1", value: "value1" }, ... ]

The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

 

 

指定URL来获取选项数据

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead the request parameter "term" gets added to the URL, which the server-side script should use for filtering the results. The data itself can be in the same format as the local data described above.

 

	<script>
	$(function() {
		$( "#tags" ).autocomplete({
			source: "search.php",
			minLength: 2,
			select: function( event, ui ) {
				// ui.item ?
				//	"Selected: " + ui.item.value + " aka " + ui.item.id :
				//	"Nothing selected, input was " + this.value;
			}
		});
	});
	</script>
 
下面使用firebug得到的search.php部分响应内容
[ { "id": "Ciconia ciconia", "label": "White Stork", "value": "White Stork" }, { "id": "Netta rufina", "label": "Red-crested Pochard", "value": "Red-crested Pochard" }, 
{ "id": "Burhinus oedicnemus", "label": "Stone Curlew", "value": "Stone Curlew" }, { "id": "Galerida cristata", "label": "Crested Lark", "value": "Crested Lark" }, 
{ "id": "Saxicola rubicola", "label": "European Stonechat", "value": "European Stonechat" }, { "id": "Circus aeruginosus", "label": "Western Marsh Harrier", "value": "Western Marsh Harrier" }, 
{ "id": "Podiceps cristatus", "label": "Great Crested Grebe", "value": "Great Crested Grebe" } ]
 

 

用回调函数来提供选项数据

使用回调函数主要有两种用途:

1、对本地的选项数据进行筛选/过滤;

2、使用ajax从远端获取选项数据;

 

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

  • A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".
  • A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

The label is always treated as text, if you want the label to be treated as html you can use Scott González' html extension. The demos all focus on different variations of the source-option - look for the one that matches your use case, and take a look at the code.

 

使用ajax获取json数据的代码样本,request.term 是用户输入的内容。

 

$(function() {
    $("#tags").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "searchAction!search.action",
                type: "POST",
                data: {
                    term: request.term
                },
                dataType: "json",
                success: function(rsp) {
                    response((rsp && rsp.data) ? rsp.data : []);  // 假定选项数据在rsp.data中
                },
                error: function() {
                    response([]);   // 出错了也要response一下,否则“忙碌”的小图标就会不停地转
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            // ui.item ? ui.item.value : this.value
        }
    });
});
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值