【问题标题】:Calling Json Web Service using AJAX in ASP.NET在 ASP.NET 中使用 AJAX 调用 Json Web 服务
【发布时间】:2013-10-16 17:44:12
【问题描述】:

任何帮助将不胜感激。

概述: 我有一个 .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>

【问题讨论】:

  • 友好提示将您的错误函数更改为此,它应该为您提供有关正在发生的特定错误的更多信息:error: function (xhr, ajaxOptions, throwedError) { alert(xhr.status);警报(抛出错误); }

标签: c# ajax json web-services


【解决方案1】:

试试

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

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

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

【讨论】:

  • 200 {"PersonName":"Jane Doe"}{"d":null} SyntaxError: 语法错误
  • @user2887262 你在火狐上测试吗?然后在其他浏览器上尝试
猜你喜欢
  • 1970-01-01
  • 2021-05-27
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 2013-07-04
  • 1970-01-01
相关资源
最近更新 更多