【问题标题】:Jquery Ajax error for asp.net pageasp.net 页面的 Jquery Ajax 错误
【发布时间】:2013-05-17 13:55:17
【问题描述】:

我有一个非常简单的页面,里面有一个[WebMethod],它返回一条简单的消息。我想在客户端通过$.ajax 显示此消息。但是我的网站正在使用重写规则,因此我的 url 对用户来说是可读的。

前: 实际网页:www.mysite.com/about // 其中包含 about 文件夹和用户控件

没有用于此的 aspx 页面,而是我使用一种方法来获取网页数据,该网页数据是实际的 html 页面并在用户控件上显示内容。

这里是 Jquery 部分。

$(document).ready(function () {
    $('.info a').click(function () {
        $.ajax({
            type: 'POST',
            url: '/about/showServer', //which url to put here
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                alert("result.d");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
        });
    });
}); 

C#

[WebMethod] // this method is in the user control
      public static string showServer()
      {
            return "Hello from server";
      }

如何使用 $.ajax 从客户端调用此方法

感谢您的时间和帮助。

编辑

我的网站有这样的结构

mysite.com/about

/about/defualt.aspx --> 加载用户控件

用户控件驻留在

mysite.com/ConLib/Custom/about.ascx/showServer

所以我把它设置成这样

url: '/ConLib/Custom/about.ascx/showServer',

但我在 XHR 请求“404 错误”中看到 chrome 开发人员工具中的错误,因为当您键入 mysite.com/conlib/blah blah ..reqrites 时不允许这样做并引发 404 错误..

【问题讨论】:

  • 正在使用网络服务吗?如果是,您是否删除了此行的注释? [System.Web.Script.Services.ScriptService]
  • 不,我很有趣的正常方法
  • 您的网络方法在哪里?在 MVC 控制器或 Webforms aspx 页面中?
  • webforms..in ascx ..请查看我的编辑

标签: asp.net jquery


【解决方案1】:

你的 ajax success 方法应该是这样的:

alert(result.d);

而不是这个:

success: function (result) {
    alert("result.d");
}

而url 应该是:

url: "Default.ascx/showServer",   // UserControlPage/MethodName

【讨论】:

  • 现在它在警告框中显示“错误”..当我在 chrome 开发人员工具中看到这个异常详细信息时:System.ArgumentException: Unknown web method showServer。参数名称:methodName..我检查方法名称和我在 jquery 中提到的完全相同 -
  • 你设置的url路径是什么?
  • 你如何在defualt.aspx页面注册你的用户控件?那里设置的路径是什么?
  • pgae 中的彻底 regiter 指令
  • 您为<%@ Register %> 指令设置的Src 是什么??
【解决方案2】:

你需要装饰你的网络方法

  [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json)]
  public static string showServer()
  {
        return "Hello from server";
  }

【讨论】:

  • 现在它在警告框中显示“错误”..当我在 chrome 开发人员工具中看到这个异常详细信息时:System.ArgumentException: Unknown web method showServer。参数名称:methodName ..我检查方法名称和我在 jquery 中提到的完全相同
  • 尝试使用 mysite.com/about/showServer 或 localhost/about/showServer 作为 url
  • url: 'localhost/ConLib/Custom/about.ascx/showServer/' 最后加/?
  • 您添加了数据:“{}”?
  • 你的本地主机是否有端口号,例如 localhost:40899/ConLib/Custom/about.ascx/showServer
【解决方案3】:

如果您的 WebMethod 位于用户控件中,则需要将其移至 ASPX 页面。看这篇文章:

How to call an ASP.NET WebMethod in a UserControl (.ascx)

url: 参数的格式应为'/MyPage.aspx/showServer'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2014-01-06
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多