1.首先建立个空的Web项目
2.将下载好的JqueryUI文件保存到JS文件加下
3.引入JS文件
1 <link href="JS/css/ui-lightness/jquery-ui-1.10.4.custom.css" rel="stylesheet" /> 2 <script src="JS/js/jquery-1.10.2.js"></script> 3 <script src="JS/js/jquery-ui-1.10.4.custom.js"></script>
4.添加Web窗体代码
1 <div> 2 <!-- Tabs --> 3 <h2 class="demoHeaders">Tabs</h2> 4 <div id="tabs"> 5 <ul> 6 <li><a href="#tabs-1">自动补全-数组</a></li> 7 <li><a href="#tabs-2">自动补全-Json</a></li> 8 </ul> 9 <div id="tabs-1"> 10 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 11 </div> 12 <div id="tabs-2"> 13 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 14 </div> 15 </div> 16 </div>
5.添加JqueryUI初始化代码
1 $(function () { 2 $("#tabs").tabs(); 3 var availableTags = ["ActionScript", "测试", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"]; 4 $("#TextBox1").autocomplete({ source: availableTags }); 5 $("#TextBox2").autocomplete({ 6 minLength: 1, source: function (request, response) { 7 $.ajax({ 8 type: "POST", 9 url: "Handler1.ashx?keyword=" + request.term, 10 contentType: "application/json; charset=utf-8", 11 dataType: "json", 12 success: function (data) { 13 response($.map(data, function (item) { 14 return { value: item }; 15 })); 16 }, 17 error: function () { 18 alert("ajax请求失败"); 19 } 20 }); 21 } 22 }) 23 });
6.创建Handler1.ashx,添加代码
1 context.Response.ContentType = "text/plain"; 2 string keyword = context.Request.QueryString["keyword"]; 3 if (keyword != null) 4 { 5 JavaScriptSerializer serializer = new JavaScriptSerializer(); // 通过JavaScriptSerializer对象的Serialize序列化为["value1","value2",...]的字符串 6 //这里应该去查询数据库,懒得写了 7 List<string> ss=new List<string> (); 8 ss.Add("adafdsa"); 9 ss.Add("dafsdf"); 10 ss.Add("dfdsfsd"); 11 string jsonString = serializer.Serialize(ss); 12 context.Response.Write(jsonString); // 返回客户端json格式数据 13 }
7.运行效果
8.更多参考资料
http://jqueryui.com/autocomplete/
练习代码下载地址 http://pan.baidu.com/s/1nt9akFf