在ASP.NET中使用AJAX调用Json Web Service

时间:2013-10-16 17:44:12

标签: c# ajax json web-services

非常感谢任何帮助。

概述: 我有一个.Net解决方案,2个项目。一个托管Web服务,一个调用Web服务。 Web服务接受整数id参数,并返回格式为JSON的人名 以下是Fiddler的原始输出:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 16 Oct 2013 16:51:18 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Content-Length: 35
Connection: Close

{"PersonName":"Jane Doe"}

这是基本的Web服务设置:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class PeopleWebService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void GetUserName(int ID)
    {
        try
        {
            using (EformTstEntities db = new EformTstEntities())
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var jsonData = new
                {
                    PersonName = (from i in db.People where i.ID == ID select i.FirstName + " " + i.LastName).FirstOrDefault()
                };
                string retJSON = js.Serialize(jsonData);
                Context.Response.Write(retJSON);
            }
        }
        catch (Exception ex)
        {
            Context.Response.Write(string.Format("[ERROR: {0}]", ex.Message));
        }

    }
}

所以,我认为Web服务工作正常而不是问题......

这是我通过ajax对Web服务的基本调用。这时我不想对输出做任何事情,我只是试图在没有错误的情况下调用Web服务。在通话中,我不断进入错误处理功能。有什么想法吗?

<script type="text/javascript">
        function getUserName() {
            var id = $("#UserID").val();
            $.ajax({
                url: "http://localhost:1211/Services/PeopleWebService.asmx/GetUserName",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: "{ID:'" + id + "'}",
                success: function (msg) {
                    alert("this worked");
                }, 
                error: function () {
                    alert("this error");
                }
            });
            return false;
        }
 </script>

1 个答案:

答案 0 :(得分:1)

尝试

data: "{'ID':'" + id + "'}",

并更改错误方法以查看错误详细信息,如下所示

error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(xhr.responseText);
    alert(thrownError);
}