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

时间:2010-05-04 20:44:03

标签: jquery asp.net-ajax webmethod

我在我的页面的代码隐藏文件中创建了一个WebMethod:

[System.Web.Services.WebMethod()]
public static string Test()
{
    return "TEST";
}

我创建了以下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>

当我点击按钮时,AJAX会关闭,但不会返回任何内容。当我调试我的代码时,方法Test()甚至不会被调用。有什么想法吗?

5 个答案:

答案 0 :(得分:6)

url: "TestPage.aspx/Test"

或任何会触及您网页的相对网址。

您可能无意中违反了same origin policy

另外,虽然你还没有,但是你期待一个d:wrap对象。因为它是你要得到一个字符串。

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

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

答案 1 :(得分:2)

我认为数据类型应为“json”。添加错误函数以查看您获得的错误状态,即404未找到,500服务器错误等等

答案 2 :(得分:1)

我用这个javascript函数使用jQuery调用WebMethods:

function pageMethod(fn, params, successFn, errorFn) {  
    var pagePath = window.location.pathname;  

    var jsonData = $.toJSON(params);

    $.ajax({  
        type: "POST",  
        url: pagePath + "/" + fn,  
        contentType: "application/json; charset=utf-8",  
        data: jsonData,  
        dataType: "json",  
        success: successFn,  
        error: errorFn  
    });
}

$ .toJson序列化是通过jquery.json-1.3插件实现的。

正如您所看到的,dataType必须是“json”

答案 3 :(得分:0)

您需要将Test()设置为接受/允许POST

答案 4 :(得分:0)

如果PageMethods在您的页面上正确注册,您应该可以使用名为PageMethods的Microsoft注册对象来调用它们。

在aspx页面加载了所有Microsoft特定库之后,您的javascript应该运行。加载后,您可以这样调用PageMethod:

PageMethods.Test(function()OnSucceeded {},function()OnFailed {});

以下是更好示例的链接:

http://www.junasoftware.com/blog/using-jquery-ajax-and-page-methods-with-a-asp.net-webservice.aspx

如果您还没有,我强烈建议您使用Firebug来帮助调试这些客户端调用。 Firebug将为您提供确定实际情况所需的所有信息。

getfirebug.com

相关问题