我在我的 ASP.NET-C# 网站上使用 JQuery UI 自动完成功能。
JavaScript:
$(function () {
var availableTags = [
<%=GetAvaliableTags() %>
];
$("input.tag_list").autocomplete({
source: availableTags
});
});
代码隐藏中的 C# 函数:
public string GetAvaliableTags()
{
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
这工作正常。但我怀疑如果我从数据库中获取大量标签,它会在页面加载时立即加载所有这些标签,从而使其变慢。我想到的有效方法是使用 Ajax。但我不是 Ajax 程序员,对此知之甚少。任何人都可以告诉我如何使用 Ajax 有效地做到这一点吗?如何按需调用GetAvailableTags
?
更新
我试过这样的:
$(function () {
var availableTags = [function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CreateTopic.aspx/GetAvaliableTags",
data: "{ 'key' : '" + $("input.tag_list").val() + "'}",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {if (result.hasOwnProperty("d")) {
$("input.tag_list").autocomplete({
source: result.d
});
}
else {
// No .d; so just use result
$("input.tag_list").autocomplete({
source: result
});
});
}];
$("input.tag_list").autocomplete({
source: availableTags
});
});
Web 方法等效于 GetAvailableTags()
[System.Web.Services.WebMethod]
public static string GetAvaliableTags(string key)
{
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
但是 Ajax 调用没有被触发。可能是什么原因?
最佳答案
我建议在服务器端使用 ASP.NET AJAX 页面方法,并让 jQuery .ajax()
函数调用它来检索数据,如下所示:
代码隐藏:
[WebMethod]
public static string GetAvailableTags()
{
// Put logic here to return list of tags (i.e. load from database)
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
标记:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetAvailableTags",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
if (result.hasOwnProperty("d")) {
// The .d is part of the result so reference it
// to get to the actual JSON data of interest
$("input.tag_list").autocomplete({
source: result.d
});
}
else {
// No .d; so just use result
$("input.tag_list").autocomplete({
source: result
});
}
}
});
});
Note: You will need to change the name of
PageName.aspx
to the name of your .aspx page. Also, the.d
syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the.d
property is there or not.
关于c# - 在 ASP.NET 中使用 JQuery UI 自动完成的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20226785/