我将以下代码用于自动完成功能。该代码之前工作正常,但当我将其复制到另一个 aspx 页面时,代码停止工作。
我已经解决了许多以前提出的相同问题,但我一无所获。这个对我帮助不大,但并没有解决我的问题。
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PGForBoys.aspx/GetAutoCompleteData",
data: "{'location':'" + document.getElementById('ContentPlaceHolder1_txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
功能代码为:
[WebMethod]
public static List<string> GetAutoCompleteData(string location)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\RoomRentDatabase.mdf;Integrated Security
=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Location from Details where Location LIKE '%'+@location+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@location", location);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Location"].ToString());
}
return result;
}
}
}