您可以將數據從您的AJAX調用傳遞給一個方法來初始化自動完成插件。
該方法可以有一個選擇器的名稱來初始化,或者如果您的選擇器在數據中,那麼您可以將數據映射到您想綁定自動完成的選擇器數組。
$(document).ready(function()
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
setAutoComplete(data);
}
});
});
function setAutoComplete(data)
{
var selectors = ["#someId", "someotherId"];
//if your selector are in the data then use data.map to get your selectors.
selectors.forEach(function(selector)
{
$(selector).autocomplete({
source: data
});
}
}
如果您的數據有特殊格式,您可以使用自定義渲染函數來初始化自動完成插件。
例如,這允許您使用類別和領域爲使用該JSON組集合組自動完成數據formModel
:
{
"Contact":{
"FirstName":"Contact.FirstName",
"MiddleInitial":"Contact.MiddleInitial",
"LastName":"Contact.LastName",
"Address1":"Contact.Address1",
"Address2":"Contact.Address2",
"City":"Contact.City",
"State":"Contact.State",
"PostalCode":"Contact.PostalCode",
"WorkPhone":"Contact.WorkPhone",
"HomePhone":"Contact.HomePhone",
"Email":"Contact.Email"
},
"UDFs":{
"ModifiedBy":"Contact.UDFs.ModifiedBy",
"ModifiedDate":"Contact.UDFs.ModifiedDate",
"SessionId":"Contact.UDFs.SessionId",
"FormData":"Contact.UDFs.FormData"
}
}
我用這個代碼:
function getFormModel() {
var availableTags = [];
for (var category in formModel) {
var fields = formModel[category];
for (var field in fields) {
availableTags.push({
category: category,
label: field,
value: fields[field] });
}
}
return availableTags;
}
function setAutoComplete(el) {
$(el).autocomplete({
source: getFormModel(),
create: function() {
//access to jQuery Autocomplete widget differs depending
//on some jQuery UI versions - you can also try .data('autocomplete')
$(this).data('uiAutocomplete')._renderMenu = customRenderMenu;
}
});
}
var customRenderMenu = function (ul, items) {
var self = this;
var categoryArr = [];
function contain(item, array) {
var contains = false;
$.each(array, function (index, value) {
if (item == value) {
contains = true;
return false;
}
});
return contains;
}
$.each(items, function (index, item) {
if (!contain(item.category, categoryArr)) {
categoryArr.push(item.category);
}
console.log(categoryArr);
});
$.each(categoryArr, function (index, category) {
ul.append("<li class='ui-autocomplete-group'>" + category + "</li>");
$.each(items, function (index, item) {
if (item.category == category) {
self._renderItemData(ul, item);
}
});
});
};
JSON從ajax調用返回的數據(成功時的數據) {「id」:1,「name」:「Customer_01」}, {「id」:2,「name」:「Customer_02」}, {「id」:3,「name」:「Customer_03 「}, {」 ID 「:4」,名稱 「: 」Customer_04「} ] 文本框」 需要將JSON的名稱字段綁定到文本框作爲自動完成 – Naveen