我是 jQuery UI 的初学者,我想使用自动完成 jQuery UI ,我编写了以下代码:
<script type="text/javascript">
$(function () {
$("#Text1").autocomplete({
source: function (request, response) {
$.ajax({
url: "Handler.ashx",
dataType: "json",
data: { term: request.term },
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.Label,
value: item.Value
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
和 HTML 代码:
<input id="Text1" type="text" />
和自动完成处理程序:
public void ProcessRequest(HttpContext context)
{
List<Customer> cuslist = new List<Customer>();
Customer cus = new Customer(1, "Mohsen");
cuslist.Add(cus);
cus = new Customer(2, "aa");
cuslist.Add(cus);
cus = new Customer(3, "bcb");
cuslist.Add(cus);
cus = new Customer(4, "cac");
cuslist.Add(cus);
cus = new Customer(5, "daad");
cuslist.Add(cus);
cus = new Customer(6, "ffaa");
cuslist.Add(cus);
cus = new Customer(7, "vvaav");
cuslist.Add(cus);
string name = context.Request.QueryString["term"];
var items = cuslist.Where(c => c.Name.Contains(name));
var list = new List<AutoComplete>();
foreach (var item in items)
{
var i = new AutoComplete {Id = item.Id, Label = item.Name, Value = item.Name};
list.Add(i);
}
string ss = JsonConvert.SerializeObject(list);
context.Response.Write(ss);
}
和自动完成类:
public class AutoComplete
{
public int Id { get; set; }
public string Label { get; set; }
public string Value { get; set; }
}
和客户类别
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public Customer(int id,string name)
{
Id = id;
Name = name;
}
}
但是当在文本框中写入时不起作用,但从客户端发送的数据是真实的
但数据不显示。请帮助我。谢谢大家
最佳答案
如果我没读错的话:
success: function (data) {
response($.map(data.Id, function (item) {
return {
value: item.Value
}
}))
},
应该是:
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Label
value: item.Value
}
}))
},
并且您的dataFilter:...
在这种情况下对您没有任何作用。
编辑:如果您使用的是 asp.net,请使用此转换器:
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
处理data.d
编辑2:基于最近的帖子: 更改为使用此(exaclty 如此处):注意 jsonp、转换器和成功处理程序更改以及 dataFilter 删除。
$("#Text1").autocomplete({
source: function(request, response) {
$.ajax({
url: "Handler.ashx",
dataType: "jsonp",
data: {
term: request.term
},
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.Label,
value: item.Value
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
关于jquery - 如何在 asp.net 中使用 jQuery UI 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10276558/