最近项目中要用到类似百度的搜索提示,要求用Jquery Autocomplete控件实现,还以为很简单(或许我太笨了搞了一天没有没搞定)。静态数据没有问题,现在关键是动态数据(从数据库中取数据返回前台)没有办法搞定,高手帮忙解决下,先在此谢过。
需求:1:用Jquery Autocomplete控件实现
2:输入两个字母后和上次比较,如果不相同则从数据库动态查询并自动提示。
3:使用.asmx或.ashx做服务
以下为我的代码,未能实现以上功能,也没找到原因。
1 <html xmlns="http://www.w3.org1999/xhtml"> 2 <head runat="server"> 3 <title>自动填充测试</title> 4 <link rel="stylesheet" type="text/css" href="lib/jquery.autocomplete.css" /> 5 <script type="text/javascript" src="lib/jquery-1.4.1.min.js"></script> 6 <script type="text/javascript" src="lib/jquery.autocomplete.js"></script> 7 <script type="text/javascript" src="lib/localdata.js"></script> 8 <script type="text/javascript"> 9 $().ready(function () { 10 $("#TxtJsion").focus().autocomplete(emails, { 11 minChars: 0, 12 width: 310, 13 max: 0, 14 matchContains: true, 15 autoFill: false, 16 formatItem: function (row, i, max) { 17 //显示的值 18 return i + "/" + max + ": \"" + row.name + "\" [" + row.to + "]"; 19 }, 20 formatMatch: function (row, i, max) { 21 //查找匹配的值 22 return row.name + " " + row.to; 23 }, 24 formatResult: function (row) { 25 //选中后的值 26 return row.to; 27 } 28 }); 29 30 $("#TxtSingle").focus(); 31 32 }); 33 34 //动态填充 35 function ActiveComplete() { 36 var keyWords = $("#TxtSingle").val(); 37 38 //改变绑定的内容 39 if (keyWords.length == 2 && keyWords != $("#TxtKey").val()) { 40 $("#TxtKey").val(keyWords); 41 $("#TxtSingle").unautocomplete(); 42 43 //填充开始 44 //$("#TxtSingle").autocomplete("http://localhost:1956/AjaxWebService.asmx/GetProvinceCitys", { 45 $("#TxtSingle").autocomplete("AutoCompSvr.aspx", { 46 extraParams: { KW: keyWords }, 47 minChars: 0, 48 mustMatch: true, 49 autoFill: false, 50 selectFirst: false, 51 scrollHeight: 220, 52 width: 640, 53 scroll: true, 54 dataType: 'json', 55 parse: function (data) { 56 return $.map(eval(data), 57 function (row) { 58 return { 59 data: row, 60 value: row.name, 61 result: row.name 62 } 63 } 64 ); 65 }, 66 67 formatItem: function (row, i, max) { 68 //显示的值 69 return i + "/" + max + ": \"" + row.name + "\" [" + row.to + "]"; 70 }, 71 formatMatch: function (row, i, max) { 72 //查找匹配的值 73 return row.name + " " + row.to; 74 }, 75 formatResult: function (row) { 76 //选中后的值 77 return row.to; 78 } 79 }); 80 //填充结束 81 82 } //end if 83 } 84 </script> 85 </head> 86 <body> 87 <form id="form1" runat="server"> 88 <div> 89 <p> 90 静态填充 91 <input type="text" id="TxtJsion" /></p> 92 <p> 93 动态填充 94 <input type="text" id="TxtSingle" onkeyup="ActiveComplete();" /> 95 <input type="hidden" id="TxtKey" value="" /></p> 96 </div> 97 </form> 98 </body> 99 </html>
其中第44行怎么也不能提交到asmx文件取值(帮忙解决一下),所以改成了aspx文件取值,虽然进入aspx.cs后台了,但是没有数据返回到前台(最关键的地方),所以也没有自动提示
AutoCompSvr.aspx.cs代码
1 using System; 2 using System.Text; 3 4 namespace AutocompleteWeb 5 { 6 public partial class AutoCompSvr : System.Web.UI.Page 7 { 8 protected void Page_Load(object sender, EventArgs e) 9 { 10 if (!IsPostBack) 11 { 12 if (Request["KW"] != null) 13 { 14 StringBuilder cytySB = new StringBuilder(); 15 16 cytySB.Append("["); 17 18 cytySB.Append("{\"name\":\"AACCASF东城区\",\"to\":\"11001\"},"); 19 cytySB.Append("{\"name\":\"AACSAWE西城区\",\"to\":\"11002\"},"); 20 cytySB.Append("{\"name\":\"AACAER海淀区\",\"to\":\"11003\"}"); 21 22 cytySB.Append("{\"name\":\"AACSFEWF浦东区\",\"to\":\"22101\"},"); 23 cytySB.Append("{\"name\":\"AACSDVB黄埔区\",\"to\":\"22102\"},"); 24 cytySB.Append("{\"name\":\"AACSDFW山海区\",\"to\":\"22103\"}"); 25 26 cytySB.Append("{\"name\":\"AAEFSDXXC越秀区\",\"to\":\"22101\"},"); 27 cytySB.Append("{\"name\":\"AACAF顺德区\",\"to\":\"22102\"},"); 28 cytySB.Append("{\"name\":\"AAXCVAS东莞区\",\"to\":\"22103\"}"); 29 30 cytySB.Append("]"); 31 32 Response.Clear(); 33 Response.ClearContent(); 34 Response.Cache.SetNoStore(); 35 Response.ContentType = "application/json"; 36 Response.ContentEncoding = System.Text.Encoding.UTF8; 37 Response.Write(cytySB.ToString()); 38 Response.Flush(); 39 Response.End(); 40 } 41 }//end IsPostBack 42 } 43 } 44 }
AjaxWebService.asmx.cs代码
1 using System.Web.Services; 2 using System.Text; 3 4 namespace AutocompleteWeb 5 { 6 /// <summary> 7 /// AjaxWebService 的摘要说明 8 /// </summary> 9 [WebService(Namespace = "http://Autocomplete.Test.Demo/")] 10 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 11 [System.ComponentModel.ToolboxItem(false)] 12 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 13 [System.Web.Script.Services.ScriptService] 14 public class AjaxWebService : System.Web.Services.WebService 15 { 16 17 [WebMethod] 18 public string HelloWorld() 19 { 20 return "Hello World"; 21 } 22 23 [WebMethod] 24 public string GetProvinceCitys(string KW) 25 { 26 StringBuilder cytySB = new StringBuilder(); 27 cytySB.Append("["); 28 cytySB.Append("{\"name\":\"AACCASF东城区\",\"to\":\"11001\"},"); 29 cytySB.Append("{\"name\":\"AACSAWE西城区\",\"to\":\"11002\"},"); 30 cytySB.Append("{\"name\":\"AACAER海淀区\",\"to\":\"11003\"}"); 31 32 cytySB.Append("{\"name\":\"AACSFEWF浦东区\",\"to\":\"22101\"},"); 33 cytySB.Append("{\"name\":\"AACSDVB黄埔区\",\"to\":\"22102\"},"); 34 cytySB.Append("{\"name\":\"AACSDFW山海区\",\"to\":\"22103\"}"); 35 36 cytySB.Append("{\"name\":\"AAEFSDXXC越秀区\",\"to\":\"22101\"},"); 37 cytySB.Append("{\"name\":\"AACAF顺德区\",\"to\":\"22102\"},"); 38 cytySB.Append("{\"name\":\"AAXCVAS东莞区\",\"to\":\"22103\"}"); 39 40 cytySB.Append("]"); 41 return cytySB.ToString(); 42 } 43 } 44 }
http://api.jqueryui.com/autocomplete/
应该是提交到ashx文件中啊,当然做成aspx也可以
这文章里有http://www.cnblogs.com/lucky_hu/archive/2012/03/31/2426924.html
使用的版本不一样,这个版本ie用不了
很多的网上的例子都是有现成的代码说明的
自己解决了,前台代码:
1 <link href="AutoLib/jquery.autocomplete.css" rel="stylesheet" type="text/css" /> 2 <script src="lib/jquery-1.4.1.min.js" type="text/javascript"></script> 3 <script src="AutoLib/jquery.autocomplete.min.js" type="text/javascript"></script> 4 <script type="text/javascript" src="lib/localdata.js"></script> 5 6 <script type="text/javascript"> 7 $().ready(function () { 8 //静态填充 9 $("#TxtJsion").focus().autocomplete(emails, { 10 minChars: 0, 11 width: 310, 12 max: 0, 13 matchContains: true, 14 autoFill: false, 15 formatItem: function (row, i, max) { 16 //显示的值 17 return i + "/" + max + ": \"" + row.name + "\" [" + row.to + "]"; 18 }, 19 formatMatch: function (row, i, max) { 20 //查找匹配的值 21 return row.name + " " + row.to; 22 }, 23 formatResult: function (row) { 24 //选中后的值 25 return row.to; 26 } 27 }); 28 29 });//初始化结束 30 31 //动态填充 32 function AutoFillKey() { 33 var keyWords = $("#<%=TxtAuto.ClientID%>").val(); 34 35 //改变绑定的内容 36 if (keyWords.length == 1 && keyWords != $("#TxtKey").val()) { 37 $("#TxtKey").val(keyWords); 38 $("#TxtAuto").unautocomplete(); 39 40 $.ajax({ 41 type: "POST", 42 url: "ServerData.ashx", 43 data: { "KW": keyWords }, 44 dataType: "json", 45 timeout: 2000, 46 error: function (data) { 47 alert("请求失败:" + data.responseText); 48 }, 49 success: function (data) { 50 AutoCompleteKey(data); 51 } 52 }); 53 54 } //end if 55 } 56 57 function AutoCompleteKey(data) { 58 //填充开始 59 $("#<%=TxtAuto.ClientID%>").autocomplete(data, { 60 minChars: 0, 61 width: 640, 62 autoFill: false, 63 matchContains: true, 64 selectFirst: false, 65 scrollHeight: 220, 66 67 scroll: true, 68 formatItem: function (row, i, max) { 69 //显示的值 70 return i + "/" + max + ": \"" + row.name + "\" [" + row.to + "]"; 71 }, 72 formatMatch: function (row, i, max) { 73 //查找匹配的值 74 return row.name + " " + row.to; 75 }, 76 formatResult: function (row) { 77 //选中后的值 78 return row.to; 79 } 80 }); 81 //填充结束 82 } 83 84 </script> 85 </head> 86 <body> 87 <form id="form1" runat="server" method="post"> 88 <div> 89 <p>静态填充<input type="text" id="TxtJsion" /></p> 90 91 <p>动态填充 92 <input type="text" id="TxtAuto" onkeyup="AutoFillKey();" runat="server" /> 93 <input type="hidden" id="TxtKey" value="" runat="server" /> 94 </p> 95 </div> 96 </form> 97 </body> 98 </html>
后台代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Script.Serialization; 6 using System.Text; 7 using System.Web.Services; 8 9 namespace AutocompleteWeb 10 { 11 /// <summary> 12 /// ServerData 的摘要说明 13 /// </summary> 14 [WebService(Namespace = "http://tempuri.org/")] 15 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 16 public class ServerData : IHttpHandler 17 { 18 19 public void ProcessRequest(HttpContext context) 20 { 21 //GET方式 22 //context.Response.ContentType = "text/plain"; 23 //string keyword = context.Request.QueryString["KW"]; 24 //if (keyword != null) 25 //{ 26 // 通过JavaScriptSerializer对象的Serialize序列化为["value1","value2",...]的字符串 27 //JavaScriptSerializer serializer = new JavaScriptSerializer(); 28 //string jsonString = serializer.Serialize(GetProvinceCitys(keyword)); 29 //context.Response.Write(jsonString); // 返回客户端json格式数据 30 //} 31 32 //POST方式 33 context.Response.ContentType = "application/json"; 34 string keyStr = ""; 35 if (context.Request["KW"] != null) 36 { 37 keyStr = context.Request["KW"].ToString(); 38 } 39 ResponseJsionStr(context, GetProvinceCitys(keyStr)); 40 } 41 42 43 /// <summary> 44 /// qinjue 2011-09-21 45 /// 返回jsion 46 /// </summary> 47 private void ResponseJsionStr(HttpContext context, string strJsion) 48 { 49 context.Response.Clear(); 50 context.Response.ClearContent(); 51 context.Response.Cache.SetNoStore(); 52 context.Response.ContentType = "application/json"; 53 context.Response.ContentEncoding = System.Text.Encoding.UTF8; 54 context.Response.Write(strJsion); 55 context.Response.End(); 56 } 57 58 public string GetProvinceCitys(string KW) 59 { 60 StringBuilder cytySB = new StringBuilder(); 61 cytySB.Append("["); 62 cytySB.Append("{\"name\":\"AACCASF东城区\",\"to\":\"11001\"},"); 63 cytySB.Append("{\"name\":\"AACSAWE西城区\",\"to\":\"11002\"},"); 64 cytySB.Append("{\"name\":\"AACAER海淀区\",\"to\":\"11003\"}"); 65 cytySB.Append("]"); 66 return cytySB.ToString(); 67 } 68 69 public bool IsReusable 70 { 71 get 72 { 73 return false; 74 } 75 } 76 } 77 }
js源码
http://files.cnblogs.com/JueGe2018/jquery.autocomplete.js
不过有个缺陷:填充后不能立刻显示出来,得填写第二个符合的字符或者输入空格后再删除空格就能出现,
谁有办法解决下。
已经解决
1 //ServerData.ashx AutoCompSvr.aspx 2 $("#TxtAuto").autocomplete("ServerData.ashx", { 3 minChars: 0, 4 max: 10, 5 width: 400, 6 matchCase: false, 7 dataType: 'json', 8 scrollHeight: 500, 9 10 //此处为传递参数 11 extraParams: { KW: "参数A" }, 12 13 //需要把data转换成json数据格式 14 parse: function (data) { 15 return $.map(eval(data), function (row) { 16 return { 17 data: row, 18 value: row.name, 19 result: row.name 20 } 21 }); 22 }, 23 formatItem: function (row, i, max) { 24 //显示的值 25 return i + "/" + max + ": \"" + row.name + "\" [" + row.to + "]"; 26 }, 27 formatMatch: function (row, i, max) { 28 //查找匹配的值 29 return row.name + " " + row.to; 30 }, 31 formatResult: function (row) { 32 //选中后的值 33 return row.to; 34 } 35 }).result(function (event, data, formatted) { 36 37 38 });
你能不能把你引用的js文件发给我啊 ?我再网上找的都不支持formatItem这几个,不知道怎么回事儿
主要问题就是 我其他都可以 就是不支持scrollHeight、format**这几个属性。。。
@湖底的鱼: 可以改变他的CSS就可以实现这些了,而且format好像升级搞成了name和value,我没啥问题了