【发布时间】:2011-10-03 08:46:31
【问题描述】:
我想为用户所在的城市构建一个 jquery 自动完成输入字段。当用户开始输入单词时,我想以这种格式显示具有最接近关联的 5 个城市的列表 [City, Country]
我有三张桌子
- 国家(id,country_name)
- 地区(id、region_name、country_id)
- 城市(id、city_name、region_id、country_id)
当用户选择一个城市时,我想捕获城市的 id 以将其插入数据库。
我应该如何使用自动完成来做到这一点?
我应该使用城市的 id 设置一个隐藏字段还是传递城市的名称,然后检查它的 id 是什么?这里的问题是全球有同名的城市,并且很难识别它。
JS代码
$("#UserCity").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://localhost/baku/users/location/",
dataType: "json",
data: {
data: request.term
},
success: function (data) {
/// Need to modify this part
response($.map(data.geonames, function (item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2
});
我从 Ajax 获得的示例 JSON 字符串
[{"name":"Banaras, Uttar Pradesh, India","city_id":"1927","region_id":"2193","country_id":"113"},{"name":"Banda, Uttar Pradesh, India","city_id":"1938","region_id":"2193","country_id":"113"},{"name":"Bangalore, Karnataka, India","city_id":"1949","region_id":"2185","country_id":"113"},{"name":"Banganapalle, Andhra Pradesh, India","city_id":"1950","region_id":"2169","country_id":"113"},{"name":"Banswara, Rajasthan, India","city_id":"1983","region_id":"2190","country_id":"113"},{"name":"Banur, Punjab, India","city_id":"1987","region_id":"2189","country_id":"113"}]
我想将名称显示为列表,并通过表单将 City_id 作为可传递参数,这样我就不需要再次进行数据库查询。
数组
Array
(
[0] => Array
(
[name] => Banaras, Uttar Pradesh, India
[city_id] => 1927
[region_id] => 2193
[country_id] => 113
)
[1] => Array
(
[name] => Banda, Uttar Pradesh, India
[city_id] => 1938
[region_id] => 2193
[country_id] => 113
)
[2] => Array
(
[name] => Bangalore, Karnataka, India
[city_id] => 1949
[region_id] => 2185
[country_id] => 113
)
[3] => Array
(
[name] => Banganapalle, Andhra Pradesh, India
[city_id] => 1950
[region_id] => 2169
[country_id] => 113
)
[4] => Array
(
[name] => Banswara, Rajasthan, India
[city_id] => 1983
[region_id] => 2190
[country_id] => 113
)
[5] => Array
(
[name] => Banur, Punjab, India
[city_id] => 1987
[region_id] => 2189
[country_id] => 113
)
)
【问题讨论】:
-
嗨..您使用哪个插件来自动完成。在 UI 自动完成插件中,它还会向您发送特定城市的 id ...jqueryui.com/demos/autocomplete/default.html
标签: php jquery mysql cakephp autocomplete