我的JavaMethod函数中的PageMethod调用未调用WebMethod。这是代码:

编辑
控制台说:

Uncaught ReferenceError: PageMethods is not defined


JS:

    function profilefollowbuttonchange(cn) {
        if (cn.className == "profile-page-owner-follow-button") {
                cn.className = "profile-page-owner-follow-button-active";
                alert("camefollow");
                PageMethods.ToggleFollow("follow", onSuccess, onFailure); //Does not trigger
                alert("camefollow"); //Doesn't get printed
            }

            else {
                cn.className = "profile-page-owner-follow-button";
                alert("cameunfollow");
                PageMethods.ToggleFollow("unfollow", onSuccess, onFailure); //Does not trigger
                alert("cameunfollow"); //Doesn't get printed
            }
    }

function onSuccess() {
}

function onFailure() {
}


C#:

[WebMethod]
public static void ToggleFollow(string command)
{
       //Does not reach this point.
}


是的,我在ScriptManager标签中添加了EnablePageMethods =“ true”标签。

但是,我在同一页面中使用了两个WebMethods来实现两个不同的目的(两个不同的名称)。这可能是问题吗?我几乎不这么认为,但是你们怎么想呢?

最佳答案

看来问题出在脚本和ScriptManager的执行顺序上。这意味着要确保Java代码可以识别PageMethods,您需要先加载ScriptManager,然后触发该Javascript函数。因此,按照我的逻辑,这里需要一个简单的更改。您需要在脚本中使用$(document).ready()来确保ScriptManager首先进入DOM,然后触发脚本。这样的事情应该在这里有所帮助。

$(document).ready(function () {
function profilefollowbuttonchange(cn) {
        if (cn.className == "profile-page-owner-follow-button") {
                cn.className = "profile-page-owner-follow-button-active";
                alert("camefollow");
                PageMethods.ToggleFollow("follow", onSuccess, onFailure); //Does not trigger
                alert("camefollow"); //Doesn't get printed
            }

            else {
                cn.className = "profile-page-owner-follow-button";
                alert("cameunfollow");
                PageMethods.ToggleFollow("unfollow", onSuccess, onFailure); //Does not trigger
                alert("cameunfollow"); //Doesn't get printed
            }
    }

function onSuccess() {
}

function onFailure() {
}
});


只需用$(document).ready()包装您的脚本代码,然后尝试。

希望这可以帮助。

09-30 13:01
查看更多