我正在使用jquery自动填充功能将城市从GeoNames加载到我页面上的文本框中:
$("#MyInput").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.geonames, function (item) {
return {
label: item.name + ", " + item.countryName,
value: item.name + " (" + item.countryName + ")" + " [" + item.countryCode + "]"
};
}));
}
});
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.label + "</strong> / " + item.value + "</a>")
.appendTo(ul);
};
此外,我正在尝试覆盖_renderItem以在我的自定义视图中显示自动填充结果,但此方法不会影响我的项目。我的代码有什么问题?您可以在jsfiddle.net/
找到示例答案 0 :(得分:1)
我刚刚想要设置文本框的“数据”。在我的情况下,我不想显示任何“数据”。我只是在执行名为data的映射时“添加”了第三个值并将其设置为“item”,然后给出了“select”部分。见下文。
$(document).ready(function () {
var $birds = $("#birds")
$birds.focus();
mURL = "my url here";
$birds.autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
url: GW.Common.getBaseURL() + "/Functions/EmailCounts/TypeAHead.aspx/country_state_city",
data: "{'text':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var jsonData = $.parseJSON(msg.d)[0].Cities;
response($.map(jsonData, function (item) {
return {
label: item.name + ', ' + item.state + ' ' + item.country,
value: item.name + ', ' + item.state + ' ' + item.country,
data: item // added as "extra"
};
}));
},
error: function (msg) {
alert(msg.status + ' ' + msg.statusText);
}
})
},
focus: function (event, ui) {
$birds.val(ui.item.label);
return false;
},
select: function (event, ui) {
log(ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value);
$birds.val(ui.item.label);
$birds.attr("data", JSON.stringify(ui.item.data)); // now you can use the extra "data" you set in success.
return false;
}
});