2013-08-17 114 views
0

我想使用Ajax调用C#函数,但调用不工作。脚本显示hello消息,但不显示成功/错误消息。我做错了什么Ajax调用c#函数不工作

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"); 
} 

回答

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'); 
       } 
     }); 
+0

现在的作品,谢谢:) :) :) – techno

+0

@techno? ??????? –

+0

他打电话的方式既不需要公开也不必须是webmethod。 – afzalulh

2

你需要在这里修复几件事。 第一张:在webforms中没有MessageBox。变更申请()方法返回的字符串:

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>