我有一个使用typeahead从数据库呈现数据的搜索框,我有一个以json格式返回值的web服务但是没有从数据库中检索数据,我可以在直接点击方法时获取值,但没有运气来自客户端,这是我的代码
<div id="test">
<input class="typeahead" type="text" placeholder="Search Code" />
</div>
<script type="text/javascript">
$(function () {
$('#test .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'codename',
displayKey: 'value',
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/service.asmx/codes") %>',
data: "{ 'coding': '" + request + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.split('-')[0],
id: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
});
});
</script>
这是我的网络服务代码
> [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] codes(string coding)
{
List<string> _articles = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["RetailMS"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Code,Code12 from Detail where " +
"Code like @coding + '%'";
cmd.Parameters.AddWithValue("@coding", coding);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
_articles.Add(string.Format("{0}-{1}", sdr["Code"], sdr["Code12"]));
}
}
conn.Close();
}
return _articles.ToArray();
}
}