我想解析下面的JavaScript数组,以用于自动完成控件。 要求是在自动完成文本框中显示值字段,并将关键字段存储为itemID。
{"Key":9886,"Value":"xxx"},{"Key":9887,"Value":"yyy"},{"Key":5634,"Value":"zzz"},{"Key":9888,"Value":"abcd"}
我尝试了下面的代码将此数组映射为文本框的源:
var itemID;
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data:JSON.stringify({'term' :request.term}),
dataType: 'json',
contentType: 'application/json',
success: function(data) {
response(
$.map(data,
function(object) {
return {
label: object.value,
value: object.key
}
})
)
},
error: function(xhr, status, error) {
alert(error);
}
});
},
minLength: 2,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.value);
itemID = ui.item.key;
}
});```
Appreciate any help on this.
答案 0 :(得分:0)
以下代码可将自动完成源映射到字典数组:
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data: JSON.stringify({ 'term': request.term }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var parsedData = JSON.parse(data);
var arr = $.map(parsedData,
function (item) {
return {
label:item.Value,
value:item.Key
}}
);
response(arr);
},
error: function (xhr, status, error) {
alert('here');
var array = [];
response(array);
}
});
},
minLength: 3,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.label);
userID = ui.item.value;
}
});
返回字典的控制器代码是这样的:
public ActionResult Getdata(string term)
{
var itemList= Provider.GetAllItems();
var filteredItems = itemList.Where(x => x.Value.Contains(term));
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(filteredItems );
return Json(result, JsonRequestBehavior.AllowGet);
}