在Asp.Net中获取jQuery Ajax返回数据

我是jQuery的新手,不明白jQuery Ajax如何返回数据。 我有一些简单的函数来获取如下的数据

[WebMethod(EnableSession = false)] protected int SignIn() { return 0; } 

在我的.aspx页面中,我有这个

 $(document).ready(function () { $("#si").click(function () { $.ajax({ type: "POST", url: "SignIn.aspx/SignIn", contentType: "application/json", success: function (txt) { alert(txt); } }); }); }); 

但在警报中我得到了整个SignIn.aspx(所有html标签等)。 如何提醒SignIn()返回的0?谢谢

您正在向ASPX文件询问数据,我认为应该是ASMX。

查看Dave Ward的post,我倾斜了所有这些: http : //encosia.com/asp-net-web-services-mistake-manual-json-serialization/

我可以做的最简单的例子如下:

添加包含的Web服务(ASMX)

 using System.Web.Services; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] public int Status(int input) { return input + 1; } } 

然后在你的HTML中做

   Test       

在ajax调用中,data中定义的字符串是web方法的输入。 名称必须匹配。 在成功回调中,第一个警报显示返回的值(输入加1),第二个警报显示它是一个数字,而不是字符串。 由于数据类型设置为JSON,因此Web方法返回JSON,允许正确键入数据。

希望这可以帮助。

使SignIn方法成为静态和公共,并使用以下代码显示警报: alert(txt.d);

试试这个样本。 我已经将id从aspx传递给handler,然后从那里返回以再次向aspx显示服务器端数据

这是示例…..

处理程序代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TestProject { ///  /// Summary description for TestHandler1 ///  public class TestHandler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { string id = context.Request["id"]; context.Response.ContentType = "text/plain"; context.Response.Write(id); } public bool IsReusable { get { return false; } } } } 

在aspx中