ASP .NET:无法使用jQuery调用Page WebMethod

Joh*_*ohn 5 jquery asp.net-ajax webmethod

我在我的页面的代码隐藏文件中创建了一个WebMethod,如下所示:

[System.Web.Services.WebMethod()]
public static string Test()
{
    return "TEST";
}
Run Code Online (Sandbox Code Playgroud)

我创建了以下HTML页面来测试它:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/></script>
    <script type="text/javascript">
        function test() {            
            $.ajax({
                type: "POST",
                url: "http://localhost/TestApp/TestPage.aspx/Test",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function(msg) {
                    alert(msg.d);
                }
            });
        }
    </script>
</head>
<body>
    <button onclick="test();">Click Me</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,AJAX会触发,但不会返回任何内容.当我调试我的代码时,该方法Test()甚至不会被调用.有任何想法吗?

Sky*_*ers 6

尝试

url: "TestPage.aspx/Test"
Run Code Online (Sandbox Code Playgroud)

或任何会打到你页面的相对网址.

您可能无意中违反了相同的原始政策.

此外,虽然您还没有,但您期待广告:包装对象.因为它是你要得到一个字符串.

这应该可以让你到达目的地.

    function test() {            
        $.ajax({
            type: "POST",
            url: "TestPage.aspx/Test",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                alert(msg.d);
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)