AutoComplete在使用者輸入時,可以根據使用者輸入給出提示。其資料來源可以來自本地,也可以使用遠端資料源,AutoComplete 的DataSource可以使用一個Function,本篇中的Function,我們使用JSONP查詢。
當資料來源為Function時,其函數定義為:
Function( Object request, Function response( Object data))
其中 request 為請求,它含有一個term屬性,為目前使用者輸入。
response 為一回呼函數,它有一個參數data,用來提示使用者的資料,這個值理應根據輸入的term進行過濾。
本例使用由genames提供的Web Service。可以查詢世界的城市名稱。使用了jQuery 提供的.ajax 函數來訪問這個Web Service.
1 $( "#city" ).autocomplete({
2 source: function( request, response ) {
3 $.ajax({
4 url: "http://ws.geonames.org/searchJSON",
5 dataType: "jsonp",
6 data: {
7 featureClass: "P",
8 style: "full",
9 maxRows: 12,
10 name_startsWith: request.term
11 },
12 success: function( data ) {
13 response( $.map( data.geonames, function( item ) {
14 return {
15 label: item.name + (item.adminName1 ? ", "
16 + item.adminName1 : "") + ", " + item.countryName,
17 value: item.name
18 };
19 }));
20 }
21 });
22 },