2011-04-03 95 views
1

抓住額外的數據,我有以下的jquery從優秀geonames.org Web服務上寫着:JQuery的自動完成和JSON飼料

$('#<%=txtFindMyCity.ClientID%>').autocomplete("http://ws.geonames.org/searchJSON", { 
      dataType: 'jsonp', 
      parse: function (data) { 
       var rows = new Array(); 
       data = data.geonames; 
       for (var i = 0; i < data.length; i++) { 
        rows[i] = { data: data[i], value: data[i].name, result: data[i].name }; 
       } 
       return rows; 
      }, 
      formatItem: function (row, i, n) { 
       $('#lat').val(row.lat); //<---- THIS 
       $('#lon').val(row.lng); //<---- AND THIS 
       return row.name + ', ' + row.adminName1 + ' ' + row.adminName2 + ' ' + row.adminName3 + row.lat + row.lng; 
      }, 
      extraParams: { 
       // geonames doesn't support q and limit, which are the autocomplete plugin defaults, so let's blank them out. 
       q: '', 
       limit: '', 
       country: '<%=Session["BusinessCountry"].ToString()%>', 
       featureClass: 'P', 
       style: 'full', 
       maxRows: 50, 
       name_startsWith: function() { 
        return $('#<%=txtFindMyCity.ClientID%>').val() 
       } 
      }, 
      max: 50 
     }).result(function (event, data, formatted) { 
      var selectedcity = $('#<%=txtFindMyCity.ClientID%>').val(); 
      $('#citymap').show('slow'); 
      $('#resultsmap').googleMaps({ 
       latitude: $('#lat').val(), 
       longitude: $('#lon').val(), 
       controls: { 
        type: { 
         control: '' 
        }, 
        zoom: { 
         control: 'GSmallZoomControl' 
        } 
       } 
       //geocode: selectedcity + ' <%=ddlCountry.SelectedItem.Text%>', 
      }); 

     }); 

我遇到的問題是,我想標示的數據。從formatItem中可以看到,該服務返回經緯度,但我不知道如何獲取它。我嘗試設置一個輸入的值 - 這種工作 - 但它只獲得了第一個數據輸入,而不是選定的。我有result(function(event, data, formatted)方法,但datadata[0|1]從不返回任何內容。

我不知所措!任何人可以提供的幫助將是真棒:)

+0

不上的問題是什麼完全清楚。你有沒有嘗試過使用'console.log()'或類似的命令來查看'formatItem()'函數中的'row'? – 2011-04-03 16:01:37

+0

感謝您的回覆no.good.at.coding :) – dooburt 2011-04-03 21:02:02

+0

哎呀,按回車...問題是我想能夠保存'row.lat'和'row.lng'時,他們被選中。否則,我只能選擇所選城市的文本 - 當有大量城市同名時,這是沒有意義的... – dooburt 2011-04-03 21:04:02

回答

2

我想現在我明白你想要做什麼,也許你怎麼能做到這一點。當您選擇某個項目時(這是result函數的意圖),您想訪問latlng的值以及name

這應該工作:

$('#<%=txtFindMyCity.ClientID%>').autocomplete("http://ws.geonames.org/searchJSON", { 
     //all your existing options go here 
    }).result(function (event, data, formatted) { 
      //access the lat, lng and name of the selected option: 
      console.log("You selected ", data.name, data.lat, data.lng); 
     }); 

    }); 
+0

no.good.at.coding,spot on!絕對完美,非常感謝:) +1 – dooburt 2011-04-04 20:17:30

+1

很高興幫助:) – 2011-04-04 20:45:01