【问题标题】:ASP.NET WebMethod returns whole page to JQuery ajax requestsASP.NET WebMethod 将整个页面返回给 JQuery ajax 请求
【发布时间】:2015-03-30 12:29:38
【问题描述】:

我正在构建一个 Web 应用程序,通过单击文本框从 jQuery 调用 ASP.NET WebMethod。问题是它返回给我整个 ASPX 页面。如何仅获取 Web 方法返回的值?这是我的代码:

$("#<%= groupNameTxt.ClientID %>").click(function () {
    $.ajax({
        url: "../UserGroups.aspx/GetGroupList",
        data: "{  }",
        // dataType: "json"
        type: "POST",
        // contentType: "application/json",
        success: function (data) { 
            alert(data);
        },
        error: function (data) { 
            alert('err');
        }
    });
});

这是我来自 CodeBehind 的 WebMethod

[System.Web.Services.WebMethod]
public static List<Groups> GetGroupList(string mail)
{
    List<Groups> empList = new List<Groups>();
    empList.Add(new Groups() { GroupID = 1, GroupName = "Admins" });
    empList.Add(new Groups() { GroupID = 2, GroupName = "Employees" });
    empList.Add(new Groups() { GroupID = 3, GroupName = "Engineers" });
    empList.Add(new Groups() { GroupID = 4, GroupName = "Managers" });
    empList.Add(new Groups() { GroupID = 5, GroupName = "Assistants" });
    return empList;
}

【问题讨论】:

  • js在哪个页面?是在 UserGroups.aspx 上吗?
  • 您确定它正在访问您的网络方法,并且您实际上没有看到错误页面的 HTML 响应,例如 404 或 500?您是否检查过控制台中的响应?
  • @PraveenPaulose 是的...它在同一个页面上。
  • 听起来你遇到了一个错误。正如我所说,检查控制台中的网络选项卡。它将显示完整的响应文本,更重要的是 HTTP 状态代码。
  • 您必须在浏览器开发工具中检查request 和response 网络调用。你已经在说你的方法没有被击中,就是问题。一个完整的猜测,因为我记得经历过类似的事情,所以要警惕redirect - 例如如果您有FriendlyUrls,那么它将您的呼叫重定向到“友好的网址”(因此更改原始请求)。

标签: javascript c# jquery asp.net ajax


【解决方案1】:

您需要将电子邮件作为参数传递,因为 webmethod 需要一个参数。

$.ajax({
    url: "../UserGroups.aspx/GetGroupList",
    data: JSON.stringify({ email: "someemail@test.com"}),
    dataType: "json"
    type: "POST",
    contentType: "application/json",
    success: function (data) { 
        alert(data);
    },
    error: function (data) { 
        alert('err');
    }
});

同时指定contentType 和dataType

【讨论】:

  • 不,,,这不是问题......即使我使用浏览器浏览 URL,我也会得到整个页面。
  • 因为您遇到了一些错误,这就是返回页面的原因。
  • 如果我使用 contentType : "application/json" 它返回我 500 - Internal Server Error 。如果我将 dataType 用作 json,则 JQuery ajax 会失败,但会获取页面作为响应。
【解决方案2】:

页面正在返回,因为它没有点击 Web 方法。下面的代码将正确命中 Web 方法。如下所示传入数据。

$.ajax({
            url: "UserGroups.aspx/GetGroupList",
            data: '{ mail: "a@a.com"}',
            dataType: "json",
            type: "POST",
            contentType: "application/json",
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert('err');

            }
        });

【讨论】:

  • 但是我正在获取页面本身 naa 吗?
  • 更新了我的答案。在本地测试过。您错误地传递了数据。我错了“../”
  • 这可能有效。但是,contentType JSON 结果我内部服务器错误(500)。也许 web.config 中的任何设置?
  • 试试 contentType="application/json; charset=utf-8"
猜你喜欢
  • 2010-09-25
  • 1970-01-01
  • 2011-10-23
  • 2010-10-09
  • 2014-06-19
  • 1970-01-01
  • 2013-06-07
  • 2011-02-04
  • 1970-01-01
相关资源
最近更新 更多