在 Web 表单中,我有以下 jQuery 设置来调用代码隐藏文件中的方法。
<script src="js/jquery-1.7.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#newBtn").click(function () {
$.ajax({
type: "POST",
url: "AJAXCaller.aspx/GetTimer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" class="link1" runat="server">Click here</a><br /><br />
<asp:LinkButton ID="newBtn" runat="server" Text="ASP Link" />
<asp:Label ID="time_lbl" runat="server" />
</div>
</form>
</body>
在后面的代码中我有以下内容:
[WebMethod]
public void GetTimer()
{
time_lbl.Text = DateTime.Now.ToString();
}
我意识到这在当前语法中不起作用。
如果我将其设置为静态,我就能够访问该方法,但我不想只返回字符串或单个值。我想访问一个方法,该方法又访问 Web 服务以返回数据集合。
我想知道是否可以执行类似的操作,我可以调用一个方法并让它更新 UI 中的字段,例如上面的方法,当调用时,服务器端脚本将为 ui 提供一个值对于日期字段?
预先感谢您的任何建议。
最佳答案
这根本不可能,因为您无法从服务器端更新 UI 上的任何字段。
不要在 aspx 页面中使用 WebMethod
,而是使用 Asp.Net Webservices 来编写可使用 ajax
调用的 Web 方法。
ajax
方法有一个成功回调,您可以在其中获取服务响应,然后通过使用适当的选择器访问它来更新 UI 字段。
例如
$(function () {
$("#newBtn").click(function () {
$.ajax({
type: "POST",
url: "AJAXCaller.asmx/GetTimer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(data){
$("#ClientIdOftime_lbl").text(data);
}
});
return false;
});
});
关于jquery - 如何使用 jQuery 从 ASP.NET 代码后面调用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283432/