2013-06-18 117 views
0

我想用AJAX请求调用一个用C#编写的简单的服务器端HelloWorld方法。用AJAX调用服务器端方法

Default.aspx的

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
    <script type ="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script> 
    <script type="text/javascript"> 
     function AjaxCall() { 
      $.ajax(
      { 
       type: 'post', 
       url: 'Default.aspx/Server_HelloWorld', 
       datatype: 'json', 
       success: function (result) { alert(result); } 
      }) 

     } 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <asp:ScriptManager ID="Scriptmanager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true"> 
     <asp:Services> 
      <asp:ServiceReference Path="TradeService.asmx" /> 
     </asp:Services> 
    </asp:ScriptManager> 
    <button id="Button2" type="button" runat="server" onclick="AjaxCall()">AJAX+JQuery version</button> 

    </form> 
</body> 
</html> 

Default.aspx.cs

namespace AJAXService 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 
     public String Server_HelloWorld() 
     { 
      return "Hello, How are you?"; 
     } 
    } 
} 

然而,而不是返回字符串, “你好,你好吗?”,我回来的HTML代码网页。有谁知道为什么发生这种情况?我最终试图让一个服务器端方法返回一个字符串,我可以使用它填充GridView单元格,利用AJAX的部分回发功能。

回答

1

试试这个

[WebMethod] 
public static String Server_HelloWorld() 
{ 
    return "Hello, How are you?"; 
} 

所以使用的WebMethod和静态。

0

使用下面的代码,并检查是否仍然面临的问题或没有,

你的Ajax调用JavaScript方法....

function AjaxCall() { 
     $.ajax(
     { 
      type: 'POST', 
      contentType: "application/json; charset=utf-8", 
      url: 'Default.aspx/Server_HelloWorld', 
      datatype: 'json', 
      success: function (result) { alert(result.d); } 
     }) 

    } 

添加下面的命名空间

using System.Web.Services; 
using System.Web.Script.Services; 

你aspx.cs Ajax Webmethod,

[WebMethod] 
[ScriptMethod] 
public String Server_HelloWorld() 
    { 
     return "Hello, How are you?"; 
    } 

希望这有助于...

1

是的,我想我知道为什么会发生这种情况!我自己也有同样的问题,并做了一些研究。

尝试使用onclick="AjaxCall(); return false;"。这取消了通常的ASP.NET onclick事件(在这种情况下,它只会返回到您的页面,这就是为什么您将页面作为响应)并且只执行JavaScript方法。

(是的,我意识到我大约2年已经太晚了,但我会在这里面对面临同样问题的人抛出)。