【问题标题】:jQuery Get() to WebMethod not workingjQuery Get() 到 WebMethod 不起作用
【发布时间】:2012-07-16 15:30:39
【问题描述】:

我正在尝试调用 jQuery 函数 $.get() 来调用我的 WebMethod,但它只会在后面的代码中触发 Page_Load 事件。我可以看到请求在 firebug 中发送到 /admin/manage-users.aspx/deleteUser?u=user1,但它从未命中 WebMethod。

jquery

$('#delete').each(function () {
    $(this).click(function () {
        var userName = $(this).closest('tr').find('span.userName').text();
        $.get('/admin/manage-users.aspx/deleteUser', { u: userName });
    });
});

aspx.cs

[WebMethod]
public void deleteUser() {
    string userName = Request.QueryString["u"];
    if(!string.IsNullOrEmpty(userName)) {
        if(Membership.DeleteUser(userName))
            Response.Redirect(Request.Url.ToString());
    }
}

解决方案

我把下面的 bugz 归功于他,因为他指出了我正确的方向。

为了让您的 [WebMethod] 在 aspx 中工作,您的方法必须是静态的

【问题讨论】:

    标签: c# jquery webmethod


    【解决方案1】:

    这里是更多信息的链接

    More Information

         $.ajax({
                        type: "POST",
                        url: "'/admin/manage-users.aspx/deleteUser'",
                        data: "{'userName ' : '" + userName + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(data) {
            //do something on success
    
                        },
                        error: function(ex) {
           //do something on failure
    
                        }
                    });    
    

    如果您返回数据或变量成功,请确保在使用 jquery/ajax 时出于某种原因使用 data.d,微软希望在变量末尾添加 .d。我花了一些时间才弄清楚。

    试试这个我猜当你调试 deleteUser 方法时永远不会被调用。

    var jqxhr = $.get("admin/manage-users.aspx/deleteUser",  { userName: userName }  function() {
        alert("success");
      })
      .success(function() { alert("second success"); })
      .error(function() { alert("error"); })
      .complete(function() { alert("complete"); });
    

    【讨论】:

    • 感谢 bugz 的回复,但这并不能真正解决我的问题。我知道 ajax() 给了我更多的灵活性,但我只是在做一个简单的 GET,get() should 工作
    • 嗯,我猜你在 deleteuser 上的断点永远不会被调用如何尝试在成功或错误事件上设置断点,看看发生了什么
    • 好主意。我今天正在处理其他一些事情,所以可能需要一两天才能回到这个项目。我会在查看您的建议时再回来查看。再次感谢!
    • ok 有机会快速查看它。它正在抛出一个 500,未知的网络方法
    • 我想通了。我的网络方法需要是静态的,之后只需要决定我是要使用 POST 还是 GET。我最终通过 POST 选择了 $.ajax() 路线。感谢您的帮助,您确实为我指明了正确的方向。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多