这让我发疯,我只是不断收到“错误”消息。我有这个使用 AJAX Toolkit 的自动完成功能,但我想尝试 JQuery,我对 JQuery 的经验很少。这是Web服务代码:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public static string GetNames(string prefixText, int count)
{
Trie ArtistTrie = new Trie();
if (HttpContext.Current.Cache["CustomersTrie"] == null)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand();
comm.CommandText = "SELECT * FROM TopArtists ORDER BY name ASC";
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = comm;
comm.Connection = conn;
conn.Open();
da.Fill(dt);
conn.Close();
Trie newtrie = new Trie();
foreach (DataRow dr in dt.Rows)
{
// topartists.Add(dr[0].ToString());
newtrie.Add(dr[0].ToString());
}
HttpContext.Current.Cache["CustomersTrie"] = newtrie;
}
ArtistTrie = (Trie)HttpContext.Current.Cache["CustomersTrie"];
List<string> list = ArtistTrie.GetCompletionList(prefixText, 10);
List<Band> list1 = new List<Band>();
foreach (string a in list)
{
Band newband = new Band();
newband.Name = a;
list1.Add(newband);
}
string json = JsonConvert.SerializeObject(list1, Formatting.Indented);
return json;
}
这是jQuery代码:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#tb1").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term ,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
})
</script>