我正在尝试使用来自网络服务的自动填充功能List<Cities>
。该列表已成功返回到函数,但返回分配不正确
我正在使用console.log来查看返回的结果,这就是我得到的结果:
console.log(itemList)
我得到:
[对象,对象,对象]
0:Object
CityId: 7932
CityName: "BADGERYS CREEK"
__type: "Cities"
__proto__: Object
1: Object
CityId: 7933
CityName: "BALGOWLAH HEIGHTS"
__type: "Cities"
__proto__: Object
2: Object
CityId: 7934
CityName: "BALMAIN EAST"
__type: "Cities"
__proto__: Objectlength: 3
__proto__: Array[0]
....
为了能够从Web服务中读取回复,我必须循环结果。我需要做一些像这样的事情,但不知道正确的语法是什么:
$("#txtDeliveryCity").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SfWebService.asmx/GetCitiesByPrefix",
dataType: "json",
data: "{'prefixText' :" + "'" + request.term + "'}"
success: function (data) {
response($.map(data, function (itemList) {
var listCityName = [];
var listCityId = [];
var counter = 0;
for (var i = 0; i < itemList.length; i++) {
listCityName[i] = itemList[i].CityName;
listCityId[i] = itemList[i].CityId;
}
// ------ This is not right:
return { label: listCityName, value: listCityId };
}));
}
});
服务器端:
public class Cities
{
public string CityName { get; set; }
public int CityId { get; set; }
{
[WebMethod]
public List<Cities> GetCitiesByPrefix(string prefixText)
{
var service = new Cities();
var cities = service.GetCityByPrefix(prefixText);
return cities;
}
答案 0 :(得分:1)
如果您在渲染文字和值字段时遇到问题,请使用以下代码。
$("#elementID")
.bind("blur", function(event) {
var currentText = $(this).html();
if (currentText === undefined || currentText === "") {
this.innerHTML = this.value = "";
}
}).autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: "your url",
data: {},cache: false,type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(datas) {response(datas.d);},
error: function(error) {alert(error.responseText);}
});
},
focus: function(event, ui) {
$(this).html(ui.item.CityName);
return false;
},
select: function(event, ui) {
$(this).html(ui.item.CityName);
$(this).attr("value", ui.item.CityId);
}
}).autocomplete("instance")._renderItem = function(ul, value) {
return $("<li></li>").data("item.autocomplete", value).append('<span value=' + value.CityId + '>' + value.CityName + '</span>').appendTo(ul);
};
这将处理自动填充的所有要求,例如按下向下箭头,向上并进入选择。 希望这会有所帮助:)