我第一次在asp.net中使用ajax。因此,我正在尝试学习一些Jquery知识。我创建了一个包含按钮的aspx文件,当点击该按钮时,它将写下当前日期。但是,当我点击按钮时,什么也不会发生。使用firebug可以看到Jscripts正在运行,但它们不会触发我的警报。有什么想法吗?
以下是代码。
这是我的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/
这是可工作的版本:
Javascript代码:
$(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();
}
}