2016-10-11 94 views
0

我背後方法下面的代碼,我想使用的JScriptPageMethods沒有定義錯誤

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> 

只有我叫它得到:Uncaught ReferenceError:PageMethods未定義

我試圖解決這個問題,但沒有辦法,需要幫助,請。

回答

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"); 
    } 
}); 
} 
+0

感謝名單anmarti,這是現在工作,但我仍然有錯誤的結果輸出是「未定義」。 –

+0

你使用'scriptManager'或'jQuery'嗎? – anmarti

+0

是的我正在使用腳本管理器,,,,現在我得到這個消息:無法讀取未定義的屬性'ajax'。 –