我正在根据用户输入生成用于自动完成的动态文本框。
var projects = [
{
label: "Test12",
desc: "responsive web application kit"
},
{
label: "Londinium",
desc: "responsive bootstrap 3 admin template"
},
{
label: "It's Brain",
desc: "Bootstrap based "
}
];
// Initialize autocomplete
$(document).on('click', '.ac-custom', function () {
$(this).autocomplete({
minLength: 0,
source: function (request, response)
{
$.ajax({
url: "/Home/GetInfo",
type: "POST",
dataType: "json",
data: { Name: $(this).val() },
success: function (data) {
}
});
},
focus: function (event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(this).val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>").append("<span class='text-semibold'>" + item.label + '</span>' + "<br>" + '<span class="text-muted text-size-small">' + item.desc + '</span>').appendTo(ul);
}
});
如果我将源代码作为项目提供,则此方法有效,但我需要从数据库中获取,因此我正在调用操作方法,但不知何故,这不起作用。 是因为我将 ajax 调用绑定(bind)到运行时创建的控件吗? 感谢您的帮助。谢谢
最佳答案
您需要传递数据以响应成功回调
// Initialize autocomplete
$(document).on('click', '.ac-custom', function () {
$(this).autocomplete({
minLength: 0,
source: function (request, response)
{
$.ajax({
url: "/Home/GetInfo",
type: "POST",
dataType: "json",
data: { Name: $(this).val() },
success: function (data) {
response( data );
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect. Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.';
}
alert(msg + "<br/>responseText: " + jqXHR.responseText);
}
});
},
focus: function (event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(this).val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>").append("<span class='text-semibold'>" + item.label + '</span>' + "<br>" + '<span class="text-muted text-size-small">' + item.desc + '</span>').appendTo(ul);
}
});
关于javascript - jquery动态自动完成文本框url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406866/