How to consume a asmx web service with jQuery?

2019-09-02 17:09发布

问题:

I have seen some many different answers on the web and did a lot of copy and paste. It just doesn't work for me. Can any one tell me why?? I am so frustrated >_< Do I have to do something on my web.config file? I don't understand that even my "WebService.asmx/add" won't return anything from my browser (because there is no such a link.) How would jQuery get any result? I must add some httphandlers, right?

回答1:

As i see in your image, your webmethod does not have static method.

A webmethod should be a static method, in order to consume a service. WebMethod and Static

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

Please go through with this links for more information

  1. WebService and Jquery


回答2:

I don't know whether I am being hated or what. There are just no people answering me. Very sad. ...>_<... After days of research, I found some way working The attribute need to serialize data as JSON string is

[System.Web.Script.Services.ScriptService]

so I have my asmx code as

<%@ 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;
}

}

my jQuery code as

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

which correctly returned 35.

NICE!