How to consume a asmx web service with jQuery?

守給你的承諾、 提交于 2019-12-13 03:11:14

问题


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!



来源:https://stackoverflow.com/questions/15342651/how-to-consume-a-asmx-web-service-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!