ASP.NET WebMethod将整个页面返回给JQuery ajax请求

ASP.NET WebMethod returns whole page to JQuery ajax requests

本文关键字:返回 JQuery ajax 请求 WebMethod NET ASP      更新时间:2023-09-26

我正在构建一个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');
        }
    });
});

这是我的WebMethod来自CodeBehind

[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;
}

您需要将电子邮件作为参数传递,因为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');
    }
});

同时指定contentTypedataType

由于页面未命中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');
            }
        });