【问题标题】:Call WebMethod from another project using Jquery使用 Jquery 从另一个项目调用 WebMethod
【发布时间】:2015-05-13 13:11:52
【问题描述】:

我在 Visual Studio 中创建了一个名为“MyProject”的项目,并向其中添加了名为“MyPage.aspx”的 .aspx 文件。

在'MyPage.aspx.cs'中有如下所示的web方法

        [WebMethod(EnableSession=true)]
        public static string GetDetails()
        {
            try
            {
                var data= HttpContext.Current.Session["mySession"] as myDto;
                return myDto.Username;
            }
            catch
            {
                return "Sorry";
            }
        }

现在,我在同一个解决方案中创建了另一个名为“NewProject”的项目。 我在这个项目中有一个页面'NewPage.aspx',我试图从'MyPage.aspx'(MyProject)调用GetDetails()。

所以我尝试了以下代码。

NewPage.aspx

 <script type="text/javascript">

        $(document).ready(function () {
            $.ajax({
                type: 'Get',
                url: 'http://localhost:2463/MyPage.aspx/GetDetails',
                success: function (data) {
                    alert(data);
                },
                error: function (response) {
                                alert('Error');
                            }
            })

        });
    </script>

但是 Web 方法没有被命中,我收到了“错误”警报。

我也试过这个

    $(document).ready(function () {
                    $.ajax({
                        type: "POST",
                        url: "http://localhost:2463/MyPage.aspx/GetDetails",
                        contentType: "application/json; charset=utf-8",
                        data: '{}',
                        datatype: "json",
                        success: function (msg) {
                            alert('success');
                        },
                        error: function (response) {
                            alert('Error');
                        }
                    });
    });

</script>

但没有运气。

请帮助...!!

【问题讨论】:

  • 查看错误中response的详细信息
  • 为什么不能使用网络服务?

标签: c# jquery asp.net ajax webmethod


【解决方案1】:

听起来像是 CORS 问题。

默认情况下,您无法访问不在源域(方案、主机名、端口)内的服务。

【讨论】:

【解决方案2】:

在进行 jquery ajax 调用时,您必须确保链接 http://localhost:2463/MyPage.aspx/GetDetails 可用。为了那个原因 您可以在一个单独的 VS 实例中运行 MyProject,然后在另一个 VS 实例中运行 NewProject。

【讨论】:

    【解决方案3】:

    在检查元素中检查控制台并找到给定错误的解决方案。 您可以调用另一个页面的 webMethod。您的代码似乎正确。 而且不需要写一个页面的整个URL('http://localhost:2463/MyPage.aspx/GetDetails'),只需要写'MyPage.aspx/GetDetails'。

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 2017-04-24
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      相关资源
      最近更新 更多