我试图用一个AJAX请求调用一个用C#编写的简单服务器端HelloWorld方法。
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的部分回发功能。
答案 0 :(得分:1)
试试这个
[WebMethod]
public static String Server_HelloWorld()
{
return "Hello, How are you?";
}
所以使用WebMethod和static。
答案 1 :(得分:1)
是的,我想我确实知道为什么会这样!我自己一直有同样的问题,并做了一些研究。
尝试使用onclick="AjaxCall(); return false;"
。这取消了通常的ASP.NET onclick事件(在这种情况下除了返回页面之外什么都不做,这就是为什么你将页面作为响应)并且只执行你的JavaScript方法。
(是的,我意识到我已经晚了2年了,但我会把它扔到这里面对那些面临同样问题的人。)
答案 2 :(得分: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?";
}
希望这会有所帮助......