用jQuery UI的autocomplete插件来实现文本框自动完成功能。
页面代码如下:
<link rel="Stylesheet" href="Scripts/jquery-ui-1.10.3/themes/base/jquery-ui.css" /> <link rel="Stylesheet" href="Scripts/jquery-ui-1.10.3/themes/base/jquery.ui.autocomplete.css" /> <script type="text/javascript" src="Scripts/jquery-ui-1.10.3/jquery-1.9.1.js"></script> <script type="text/javascript" src="Scripts/jquery-ui-1.10.3/ui/jquery-ui.js"></script> <script type="text/javascript" src="Scripts/jquery-ui-1.10.3/ui/jquery.ui.autocomplete.js"></script> <script type="text/javascript"> jQuery(function () { jQuery("#iptbook").autocomplete({ source: function (request, response) { jQuery.ajax({ url: "AutoComplete.aspx", dataType: "xml", data: { key: escape(request.term), ts: new Date().getSeconds() }, success: function (data) { response(jQuery("Book", data).map(function () { return { value: jQuery("title", this).text(), title: jQuery("title", this).text() } })); } }); }, minLength: 1, select: function (event, ui) { alert(ui.item.title); } }); }); </script> <input type="text" id="iptbook" name="iptbook" value="" />
后台代码 输出XML格式数据
protected override void OnLoad(EventArgs e) {
//简化为直接输出xml
StringBuilder xml = new StringBuilder(); xml.Append("<?xml version="1.0" encoding="gb2312"?>"); xml.Append("<Books>"); xml.Append("<Book><id>1</id><title>C#高级编程</title></Book>"); xml.Append("<Book><id>2</id><title>JavaScript高级程序设计</title></Book>"); xml.Append("</Books>"); Response.Write(xml.ToString()); try { Response.End(); } catch (Exception ex) { } base.OnLoad(e); }