如何在Ajax调用中传递正确的Web服务URL

时间:2014-11-24 13:48:33

标签: jquery asp.net ajax web-services

我有一个asp.net Web服务,其中包含一个我必须通过Ajax jquery调用的方法。现在我已经将这个Web服务发布并部署到IIS中,通过localhost,我可以访问这个Web服务和Web方法。 / p>

以下是本地主机上的WebMethod的URL ..

http://localhost/app/DateWebService.asmx/GetData

现在根据我的要求,我需要从jquery Ajax调用按钮Click Event调用此WebMethod GetData。现在,只要我点击按钮,我就可以看到成功的方法中的警报消息ajax但看不到回复.. 对于响应,我在控制台中出现以下错误

TypeError: msg is null
$("#output").text(msg.d);

这是我的Ajax Call代码..

        $("#Button1").click(function () {

            var Name = "asdfg";
            var Contact = "79749497979";
            var Email = "hr@gmail.com";

            $.ajax({
                type: "POST",
                url: "http://localhost/app/DateWebService.asmx/GetData",
                data: '{"Name":"' + Name + '","Contact":"' + Contact + '","Email":"' + Email + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {

                    $("#output").text(msg.d);
                }
            });
        });

请帮我解决这个错误..提前谢谢..

这是我的WebMethod代码..

  [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetData(string Name, string Contact, string Email)
{
    return Name + Contact + Email;
}

2 个答案:

答案 0 :(得分:1)

我得到了解决方案。问题在于权限。我在客户端代码中添加了一行..i.e

crossDomain: true,

并在我的Web服务的Web.config文件中添加了这两行。

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

喜欢这个

<system.webServer>

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

<defaultDocument>
  <files>
    <add value="DateWebService.asmx" />
  </files>
</defaultDocument>

我得到了它..

答案 1 :(得分:0)

data: JSON.stringify('{"Name":"' + Name + '","Contact":"' + Contact + '","Email":"' + Email + '"}'),