我使用geonames.org自动完成城市和州,但发现它太慢而不可靠。我的代码如下,并且确实有效(等待大约10秒钟才能看到自动完成结果)
旧(工作)代码:http://jsbin.com/umewo3/2/edit
$(function() {
$( "#sf_city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
country: 'US',
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
value: item.name + (item.adminName1 ? ", " + item.adminCode1 : "")
}
}));
}
});
},
minLength: 2
});
});
现在我正在使用YQL,因为它们提供了更快的响应。问题是我似乎不明白如何正确映射响应。你可以看到我正在发送一个格式正确的请求,然后回复 - 但我不知道如何正确处理响应。
这里有新的(损坏的)代码:http://jsbin.com/aqoke3/2/edit
$(function() {
$( "#sf_city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
dataType: "json",
data: {
q: 'select name,admin1.code from geo.places where text="' + request.term + '*" and country.code="US" limit 10 | sort(field="popRank", descending="true")',
format: 'json',
callback: 'cbfunc'
},
success: function( data ) {
response( $.map( data.query.results.place, function( item ) {
return {
value: item.name
}
}));
}
});
},
minLength: 2
});
});