当我点击以下 div 时:
<div id="Result">Click here for the time.</div>
我需要运行以下代码隐藏函数:
<WebMethod()> _
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
我需要用 GetDate() 函数返回的字符串填充 div 内部。我认为这应该使用与此类似的代码:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
</script>
我从这个网站中提取了这个示例:http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
但是,我根本无法让它工作。什么都没发生。这只是一个常规的 ASP.NET Web 项目。除了在我的标记中包含脚本标签来引用 jquery 之外,我没有做过任何类型的支持 Ajax 的业务。
以下是当我单击 div 时 Firebug 控制台告诉我的内容:
POST http://admin/Default.aspx GetDate 404 Not Found -18ms
编辑:注意:test.aspx/GetDate 必须与您的 aspx 页面名称和函数名称匹配!
最佳答案
<WebMethod()> _
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
必须是“共享”(C# 中的“静态”)
关于ASP.NET 4.0 - 使用 Jquery,如何调用代码隐藏函数并将数据返回给客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4111033/