jQuery 入门教程(25): jQuery UI Autocomplete示例(三)

jerry JQuery 2015年08月24日 收藏

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. },

20130316005