使用jQuery调用asmx Web服务

时间:2013-06-05 10:28:08

标签: jquery web-services asmx

我正在尝试使用jQuery调用.NET asmx Web服务。我一直在使用指南herehere,据我所知,我已经跟着他们去了这封信。

服务代码:

[WebService(Namespace = "http://tempuri.org/", Description = "...")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class MyService : WebService
{

    private static readonly IKernel NinjectKernel = new StandardKernel(new IocModule());

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public string HelloWorld(string name)
    {
        return string.Format("Hello {0}", name);
    }

我很乐意浏览Firefox中的服务并调用HelloWorld方法。

客户端jQuery:

    if (ajaxRunning) {
        return;
    }
    ajaxRunning = true;

    var webMethod = "http://localhost:51546/MyService.asmx/HelloWorld";
    var inputname = "Jack";

    $("[id$='spinner']").show();
    $("[id$='spinnerText']").show();

    $.ajax({
        type: "POST",
        url: webMethod,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {name: inputname},
        success: function (msg) {
            $("[id$='spinner']").hide();
            $("[id$='spinnerText']").hide();
            ajaxRunning = false;
            alert(msg.d);
        },
        error: function() {
            $("[id$='spinner']").hide();
            $("[id$='spinnerText']").hide();
            ajaxRunning = false;
            alert("Fail");
        }
    });

当我运行javascript时,Firebug中没有错误,只有“失败”警告弹出窗口。请告诉我,我是否做了明显错误的事情?

提前致谢

1 个答案:

答案 0 :(得分:1)

需要对发送到WebService的参数进行字符串化。 的:

data: {name: inputname}

需要替换为:

data: JSON.stringify({name: inputname})
相关问题