繁体   English   中英

在ASP.NET中使用AJAX调用Json Web服务

[英]Calling Json Web Service using AJAX in ASP.NET

任何帮助将不胜感激。

概述:我有一个.Net解决方案,两个项目。 一个承载一个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>

尝试

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM