我有jQuery代码,它看起来像这样:
var FoundBanks = [];
function search() {
$.ajax({ url: "/bankir/banks_search/",
data: { term: $("#search").val()},
dataType: 'json',
type: "POST",
success: function(data){
FoundBanks = [];
for (var i in data) {
if (typeof(data[i]) == "object") {
FoundBanks.push(data[i]);
}
}
$("#search").autocomplete({
source: FoundBanks,
minLength: 0,
focus: function (event, ui) {
$("#search").val(ui.item.name);
return false;
},
select: function (event, ui) {
window.location = "/bank/"+ui.item.id;
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
console.log("renderitem");
return $("<li>")
.append("<a>" + item.name + "</a>")
.appendTo(ul);
};
}
});
}
它对基于MVC的后端进行查询,在json中得到结果(有效结果,我检查过),形成一个数组。
例如,形成的数组如下所示:
[{id: "1", name:"abc"}, {id:"2", name: "bac"}, {id: "3", name: "cab"}]
如果我输入&#34; a&#34; - 我什么也看不见,但当我删除&#34; a&#34; - 我看到了这三个。所以看起来jQuery并不知道它应该在object.name
中寻找一个值。
答案 0 :(得分:1)
你不需要为它调用函数:
只有一个输入元素:
<input type="text" id="search">
试试这个:
$(function(){
$("#search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/bankir/banks_search/",
type: "POST",
dataType: "jsonp",
data: {
term: $("#search").val()
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
minLength: 0,
focus: function(event, ui) {
$("#search").val(ui.item.label);
},
select: function(event, ui) {
window.location = "/bank/" + ui.item.value;
}
});
});