【发布时间】:2011-08-09 10:12:28
【问题描述】:
我第一次在 asp.net 中使用 ajax。在那里,我正在尝试学习一些 Jquery。我创建了一个包含一个按钮的 aspx 文件,当单击它时,它将记下当前日期。目前,当我单击按钮时没有任何反应。我可以看到 Jscripts 通过使用 firebug 正在运行,但它们不会触发我的警报。有什么想法吗?
代码如下。
这是我的 Jscript:
$(document).ready(function () {
$("#Result").click(function () {
alert("Before Ajax");
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('About to replace content');
$("#Result").text(msg.d);
}
});
});
});
这是我的 aspx 文件:
<html>
<head>
<title></title>
<script src="jquery/JScript1.js" type="text/javascript"></script>
<script src="jquery/jquery-1.6.2.min.js" type="text/javascript"></script>
</head>
<body>
<form runat="server">
<input id="Result" type="submit" value="Click here for the time."/>
</form>
</body>
</html>
这是我的 aspx 代码隐藏:
public partial class index : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
使用示例:http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
这是工作版本:
Jscript:
$(document).ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "index.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('About to replace content');
$("#Result").val(msg.d);
}
});
});
});
aspx:
<html>
<head>
<title>Calling a page method with jQuery</title>
<script src="jquery/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="jquery/JScript1.js" type="text/javascript"></script>
</head>
<body>
<form runat="server">
<input id="Result" type="button" value="Click here for the time." />
</form>
</body>
</html>
代码隐藏:
public partial class index : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
【问题讨论】:
-
您在 FireBug 中有任何错误吗? HTTP POST 的响应显示什么?
-
仔细检查包含静态GetDate方法的文件名,是Index.aspx的Default.aspx吗?
-
您应该从问题中删除解决方案并将其添加为答案。