如何使用jQuery使用asmx Web服务?

我在网上看到了很多不同的答案,并做了大量的复制和粘贴。 它对我不起作用。 谁能告诉我为什么? 我很沮丧> _ <我是否必须在我的web.config文件上做一些事情? 我不明白,即使我的“WebService.asmx / add”也不会从我的浏览器返回任何内容(因为没有这样的链接。)jQuery将如何得到任何结果? 我必须添加一些httphandler,对吗? 在此处输入图像描述

正如我在您的图像中看到的,您的web方法没有静态方法。

webme方法应该是静态方法,以便使用服务。 WebMethod和Static

[WebMethod] Public static string HelloWorld() { return "Hi"; } 

请仔细阅读此链接以获取更多信息

  1. WebService和Jquery

我不知道我是被憎恨还是被憎恨。 没有人回答我。 很伤心。 …> _ <...经过几天的研究,我发现了一些工作方式属性需要按照JSON字符串序列化数据

 [System.Web.Script.Services.ScriptService] 

所以我有我的asmx代码

 <%@ WebService Language="C#" Class="WebService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Web.Script.Services; using System.Data; using System.Data.SqlClient; [System.Web.Script.Services.ScriptService] [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string HelloWorld() { return "Hello World"; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public int add(int a, int b) { return a + b; } 

}

我的jQuery代码为

  $( function () { $.ajax({ type: "POST", url: 'WebService.asmx/add', data: "{'a':15, 'b':20}", //be careful! do pass it as a string contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg.d); }, error: function (e) { alert("WebSerivce unreachable"); } }); } ); 

正确返回35。

NICE!