我的前端有一个文本框,我试图根据sql查询带来的内容实现自动建议。我正在使用jquery库并将它们导入到我的解决方案中。当我继续运行它时,它会击中"无匹配错误"虽然我在搜索框中输入了一个字母。我在代码中遗漏了什么吗?
下面的aspx代码:
<link href="jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#SearchBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CompanyPage.aspx/GetCompanyName",
data: "{'cmpName':'" + document.getElementById('SearchBox').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Match");
}
});
}
});
}
</script>
<asp:TextBox ID="SearchBox" placeholder="Enter company name to search on" runat="server" Width="322px" Height="16px" style="margin-left: 22px; margin-top: 0px" OnTextChanged="SearchBox_TextChanged"></asp:TextBox>
aspx.cs代码:
[WebMethod]
public static List<string> GetCompanyName(string cmpName)
{
List<string> cmpResult = new List<string>();
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand("[searchCompanyName]", cn))
{
cmd.Connection = cn;
cn.Open();
cmd.Parameters.AddWithValue("@CompanyName", cmpName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cmpResult.Add(dr["CompanyName"].ToString());
}
cn.Close();
return cmpResult;
}
}
SQL存储过程:
ALTER PROCEDURE [dbo].[searchCompanyName]
@CompanyName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT CompanyName FROM Company
WHERE CompanyName like @CompanyName + '%'
END
答案 0 :(得分:0)
AJAX:
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CompanyPage.aspx/GetCompanyData",
data: "{'companyname':'" + document.getElementById('SearchBox').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {
response(data.d);
}
},
error: function (result) {
alert("Error");
}
});
}
});
}
ajax.cs
[WebMethod]
public static List<string> GetCompanyData(string companyname)
{
List<string> result = new List<string>();
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("[searchCompanyName]", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("@companyname", companyname);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["companyname"].ToString());
}
return result;
}