【问题标题】:Make jQuery Ajax Call on Master Page?在母版页上进行 jQuery Ajax 调用?
【发布时间】:2010-09-09 03:41:55
【问题描述】:

我错过了什么吗?我正在尝试使用 jquery 对我网站上的 Web 服务进行简单的 ajax 调用,每次从母版页进行调用时都会收到 500 错误。没有人从母版页进行过 ajax 调用,还是我只是疯了并且极度缺乏睡眠?

例子:

MasterPage.master

<script type="text/javascript">
    $(document).ready(function () {
        $.ajaxSetup({ dataType: "json", contentType: "application/json; charset=utf-8" });

        $.ajax({
            url: '<%= ResolveUrl("~/Services/Test.asmx/HelloWorld") %>',
            success: function (data) {
                alert(data);
            },
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            }
        });

    });
</script>

/Services/Test.asmx

<WebMethod()> _
Public Function HelloWorld() As String
   Return "Hello World"
End Function

看出什么问题了吗?我对母版页有误解吗?请帮忙!

【问题讨论】:

  • 没有什么特定于 MasterPage 会导致这种情况。你是说当你的代码在视图页面而不是母版页中时它有效吗?
  • 您在浏览器中加载~/Services/Test.asmx/HelloWorld 时是否也收到500 错误?
  • 尝试检查 IIS 日志等
  • 我可以“浏览”到我的 web 服务页面 (~/Services/Test.asmx/HelloWorld) 并且加载正常。该方法可用,我可以调用它。即将验证我是否能够在内容视图页面上查看 Web 服务。
  • 请求格式无法识别,因为 URL 意外以“/HelloWorld”结尾。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。异常详细信息:System.InvalidOperationException:无法识别 URL 意外以“/HelloWorld”结尾的请求格式。源错误:[InvalidOperationException:无法识别请求格式,因为 URL 意外以“/HelloWorld”结尾。]

标签: asp.net jquery ajax web-services master-pages


【解决方案1】:

好的,我相信我已经找到了问题所在。现在我开始认为我只是困了。我遇到的几个问题,我会列出给其他人,以确保他们将来不会这样做:

1) 我记得之前读过另一篇文章,其中解释说通过 jQuery 库的 ajax 调用不喜欢数据的空对象,因此即使它是空数组也必须列出某些内容。所以,这正是我添加的内容:

$.ajax({
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: 'POST',
            data: [],
            url: '<%= ResolveUrl("~/Test.asmx/HelloWorld") %>',
            success: function (data) {
                alert(data);
            },
            error: function (xhr, err) {
                //alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                //alert("responseText: " + xhr.responseText);
                $('#ajaxResponse').html(xhr.responseText);
            }
        });

2) 一旦我解决了 jQuery ajax 问题,我就会收到来自 Web 服务本身的错误消息。警告我要能够从脚本调用 Web 服务,我必须添加以下行:

<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Test
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "[{""Hello World""}]"
    End Function

End Class

这解决了它,现在我可以在任何地方调用它。感谢您的帖子,但看起来我只是像往常一样忽略了一些事情......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多