Ais*_*iva 4 javascript c# asp.net ajax jquery
我在我的ASP.NET-C#网站上使用JQuery UI Autocomplete.
JavaScript的:
$(function () {
var availableTags = [
<%=GetAvaliableTags() %>
];
$("input.tag_list").autocomplete({
source: availableTags
});
});
Run Code Online (Sandbox Code Playgroud)
代码隐藏中的C#函数:
public string GetAvaliableTags()
{
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
Run Code Online (Sandbox Code Playgroud)
这工作正常.但我怀疑如果我从数据库中获取大量标签,它会立即在页面加载时加载所有这些标签,使其变慢.我想到的有效方法是使用Ajax.但我不是Ajax程序员,对此知之甚少.任何人都可以告诉我如何有效地使用Ajax吗?如何GetAvailableTags按需打电话?
UPDATE
我试过这样的:
$(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
});
});
Run Code Online (Sandbox Code Playgroud)
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)));
}
Run Code Online (Sandbox Code Playgroud)
但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)));
}
Run Code Online (Sandbox Code Playgroud)
标记:
$(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
});
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
注意:您需要将名称更改为
PageName.aspx.aspx页面的名称.此外,.d语法是Microsoft在ASP.NET AJAX的ASP.NET 3.5版本中提供的反XSS保护; 因此,检查.d财产是否存在.
| 归档时间: |
|
| 查看次数: |
15878 次 |
| 最近记录: |