这是我的代码:
<script type="text/javascript">
$(document).ready(function () {
$(".list tr:even").addClass("even");
var cityList = [];
$("#autocomplete").autocomplete({
source: function () {
$.ajax({
type: "POST",
url: "flight/fillcitydropdownlist",
data: "{'cityname':'" + $('#autocomplete').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.cities.length > 0) {
for (var i = 0; i < data.cities.length; i++) {
cityList.push(data.cities[i].Main);
}
}
return cityList;
}
})
}
})
});
我不明白为什么这不起作用。 ul元素添加在页面底部,但没有添加任何符号。虽然cityList已经填满。问题与我如何将数组传递给autocompelet源有关吗?
答案 0 :(得分:3)
你不能从source函数返回一个值,它接收一个回调函数作为第二个参数,一旦响应返回你需要将响应数据传递给回调函数
$(document).ready(function () {
$(".list tr:even").addClass("even");
var cityList = [];
$("#autocomplete").autocomplete({
source: function (request, callback) {
$.ajax({
type: "POST",
url: "flight/fillcitydropdownlist",
data: "{'cityname':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
callback($.map(data.cities, function(obj){
return obj.Main
}))
}
})
}
})
});