【问题标题】:Sitecore, jQuery ajax, and WebMethod returns the page itselfSitecore、jQuery ajax 和 WebMethod 返回页面本身
【发布时间】:2012-07-02 16:46:34
【问题描述】:

我正在尝试使用 jQuery ajax 在我的应用程序中的 aspx 页面上调用 WebMethod。我在关注这篇文章:http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

我注意到,当我尝试进行 ajax 调用时,它给了我页面本身 (myPage.aspx),而不是我的 WebMethod 的结果。在这一点上,我基本上是直接使用上面文章中的代码。 javascript是:

$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
    $.ajax({
        type: "POST",
        url: "myPage.aspx/GetDate",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Replace the div's content with the page method's return.
            $("#Result").text(msg.d);
        }
    });
});
});

WebMethod 的 myPage.aspx 代码隐藏为:

    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }

奇怪的是我让它在一个单独的测试页面上工作,但是当我试图将它集成到我想要使用它的实际页面中时,它没有。在搜索网站和网络时,我找不到任何解决我问题的方法。

我正在运行 Sitecore 6.5 和 .NET Framework 4.0 版。任何人都可以提供帮助或提供见解吗?

【问题讨论】:

  • 为什么不包含像这样的错误函数错误:function (xhr, status, error) { var msg = JSON.parse(xhr.responseText); alert(msg.Message);} 并查看它是否抛出任何错误或使用 firebug 检查请求和响应
  • @user1042031 我之前查看了响应标头,它返回的是页面本身的 HTML 文本/html。我不太确定为什么会这样。

标签: jquery ajax sitecore webmethod


【解决方案1】:

我只熟悉 PHP,但通常你必须在返回之前对你的数组进行 json_encode()。所以例如在php中

$TestArray['d'] = "All My HTML";
echo json_encode($TestArray);

//Then in Jquery

$("#Result").html(msg.d);

并确保有一个 id 为 Result 的 div...

【讨论】:

    【解决方案2】:

    通常,当请求不是 POST 或没有设置 application/json Content-Type 时会发生这种情况。

    我对 Sitecore 不熟悉,但其他人似乎在干扰页面方法时遇到了麻烦:How to use jquery ajax and webmethod with sitecore

    【讨论】:

      【解决方案3】:

      我认为问题在于 Sitecore 的 URL 重写器将处理请求并忽略您的 url 的 /GetDate 部分。

      因此,您必须将您的 aspx 添加到 <setting name="IgnoreUrlPrefixes" /> 设置中。

      【讨论】:

      • 我向 Sitecore 提交了一张支持票,他们回复说这是由 RewriteModule 中的问题引起的。他们确实说它在 6.5-Update 4 中无法重现,因此升级 Sitecore 可能会奏效,但我现在无法这样做。我确实尝试将我的页面添加到 IgnoreUrlPrefixes 设置,但这没有帮助。感谢您的回复!
      • 这不是一个选项,因为您会丢失 Sitecore 上下文
      猜你喜欢
      • 2010-09-25
      • 1970-01-01
      • 2014-06-19
      • 2011-06-09
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      • 2010-10-09
      相关资源
      最近更新 更多