我正在尝试使用Ajax来调用C#函数,但是调用不起作用。脚本显示了hello消息,但没有显示成功/错误消息。我做错了什么
Java脚本
<script type="text/javascript">
$(document).ready(function () {
$('#btnsave1').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function () {
alert('Successfully Saved');
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
C#方法
protected void apply()
{
MessageBox.Show("hi");
}
答案 0 :(得分:2)
试试这个:
[WebMethod]//write [WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
data:'{}',
success: function (result) {
alert(result);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
答案 1 :(得分:2)
这里你需要解决的几件事情。 首先: webforms中没有MessageBox。将apply()方法更改为返回字符串:
protected string apply()
{
return "hi!";
}
第二:使用'#btnsave1'
到'#<%= btnsave1.ClientID %>'
获取按钮的服务器生成ID,并捕获apply()方法返回的字符串。您的脚本应如下所示:
<script type="text/javascript">
$(document).ready(function () {
$('#<%= btnsave1.ClientID %>').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function (data) {
alert(data);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
</script>
第三:确保您在页面的头部引用了jquery:
<head runat="server">
<script src="Scripts/jquery-1.8.2.js"></script>