PageMethods未定义错误

时间:2016-10-11 07:10:42

标签: javascript asp.net

我在方法后面有以下代码,我想用JScript调用它

VB代码

   <WebMethod>
    Public Shared Function SayHello() As String
        Return ("Hello JScript")
    End Function

ASPX

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script  type="text/javascript">
        function GetMessage() {
            var i = PageMethods.SayHello();
            document.write(i);
        }
        setInterval(GetMessage, 500);
    </script>
</head>
<body>
</body>
</html>

只有我得到:未捕获的ReferenceError:未定义PageMethods

我试图解决这个问题但是没有办法,需要帮助。

1 个答案:

答案 0 :(得分:1)

您在标记中修改了Microsoft Ajax Extensions。

<asp:ScriptManager ID="ScriptManager1" 
EnablePageMethods="true" 
EnablePartialRendering="true" runat="server" />

<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
     <title></title>
       <script  type="text/javascript">
          function GetMessage() {
             PageMethods.SayHello(callBack);
           }

           function callBack(result, userContext, methodName){
                 alert(result);
           }
           setInterval(GetMessage, 500);
        </script>
      </head>
     <body>
     </body>
</html>

尽管这是一个有效的方法,但我更喜欢使用jQuery调用页面方法(不需要MS ajax扩展):

你需要jQuery库:

<script   src="http://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>


function GetMessage() {
 $.ajax({
    type: "POST",
    url: "PageMethods.aspx/SayHello",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
        alert(response.d);
    },
    failure: function(response) {
        alert("Error");
    }
 });
}