我们用谷歌、百度查东西的时候,浏览器会根据我们在搜索框中输入的关键字给出几个相似的提示项供选择。
在Asp.net Web开发中有时我们也需要实现这个功能,接下来我们借助jquery插件jquery-ui来达到这种效果,插件官网为:http://jqueryui.com/autocomplete/,大家在下载的时候注意只选择autocomplete部分,否则把其他功能的代码也一并下载下来没卵用。
引入js、css文件
<script src="JS/Autocomplete/external/jquery/jquery.js" type="text/javascript"></script>
<script src="JS/Autocomplete/jquery-ui.js" type="text/javascript"></script>
<link href="JS/Autocomplete/jquery-ui.css" rel="stylesheet" type="text/css" />
基本固定数据写法
<script type="text/javascript">
$(document).ready(function () {
var availableTags = [
"Asp","BASIC","C",
"C++","Java","JavaScript",
"Lisp","Perl","PHP",
"Python","Ruby"
];
$("#autocomplete").autocomplete({
source: availableTags
});
});
</script>
<body>
<form id="form1" runat="server">
<div>
编程语言:<input type="text" id="autocomplete" class="ui-widget" />
</div>
</form>
</body>
这个基本例子很简单,不过有两个知识点必须了解:
1、文本框提示的内容来源于符合特定格式的静态数据或动态数据(此处展示的是静态数据)
2、source的数据源必须是json数组,不能是其他格式的内容,否则没效果
请求aspx动态获取source数据
前台代码:
<script type="text/javascript">
$(document).ready(function () {
var availableTags = [
"Asp","BASIC","C",
"C++","Java","JavaScript",
"Lisp","Perl","PHP",
"Python","Ruby"
];
$.ajax({
type: "POST",
url: "AjaxPage.aspx/GetAllHints",
contentType: "application/json",
//data必须用双引号引起来
data: "{ action: 'autoComplete', value: 'guo' }",
dataType: "json",
async: false,
success: function (msg) {
//将后台返回的数据转换成json数组形式
var datas = JSON.parse(msg.d);
//修改数据源的值
availableTags = datas;
$("#autocomplete").autocomplete({
source: availableTags
});
}
});
});
</script>
aspx后台代码:
[WebMethod]
public static string GetAllHints(string action,string value)
{
string strResult = "[\"guo\",\"tong\",\"chang\",\"wang\",\"hao\",\"bang\"]";
return strResult;
}
请求ashx动态获取source数据
前台代码:
<script type="text/javascript">
$(document).ready(function () {
var availableTags = [
"Asp","BASIC","C",
"C++","Java","JavaScript",
"Lisp","Perl","PHP",
"Python","Ruby"
];
$.ajax({
type: "POST",
url: "Handler1.ashx",
contentType: "application/json",
//data不必用双引号引起来【不同点1】
data: { action: 'autoComplete', value: 'guo' },
dataType: "json",
async: false,
success: function (msg) {
//不需要将后台返回的数据转换成json数组形式【不同点2】
//修改数据源的值
availableTags = msg;
$("#autocomplete").autocomplete({
source: availableTags
});
}
});
});
</script>
两个不同点指的是从aspx动态获取数据与从ashx动态获取数据之间的不同之处。
ashx后台代码:
public void ProcessRequest(HttpContext context)
{
string strResult = "[\"guo\",\"tong\",\"chang\",\"wang\",\"hao\",\"bang\"]";
context.Response.Write(strResult);
}