2014-01-08 21 views
1

text.ascx CODE:如何使用jQuery阿賈克斯與asp.net用戶控件

<script type = "text/javascript"> 
    function ShowCurrentTime() { 

     $.ajax({ 
      type: "POST", 
      url: "TestAjax.aspx/GetCurrentTime", 
      data: '{}', 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: OnSuccess, 
      failure: function (response) { 
       alert(response.d); 
      } 
     }); 
    } 
    function OnSuccess(response) { 
     alert(response.d); 
    } 

<input type="checkbox" id='chkl' onclick=ShowCurrentTime();>'; 

text.ascx.cs代碼:

[System.Web.Services.WebMethod] 
public static string GetCurrentTime(string name) 
{ 
    return "Hello " + name + Environment.NewLine + "The Current Time is: " 
     + DateTime.Now.ToString(); 
} 

如何調用用戶控件中的jquery ajax。

+0

的不可能性重複:http://stackoverflow.com/questions/3201218/how-can-i-call-webmethod-which-is-defined-in-user-control –

回答

0

你可以嘗試這樣的:

$.ajax({ 
     type: "POST", 
     url: "*name.ascx/method", 
     data: { } , 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (msg) { 
      var URL = msg.d; 
      alert(URL); 
      } 
     )}; 

希望這有助於..

+0

ShowCurrentTime(),它的功能我必須調用usercontrol頁面 –

+0

我不認爲你可以調用在.ascx用戶控件中聲明的頁面方法。它必須位於.aspx頁面或.asmx Web服務中。 –

2

不能調用的WebMethod在用戶控件。嘗試在WebPage中使用WebMethod來代替。

看一看Already answered here

0

你可以試試這個代碼。

$.ajax({ 
    type: "POST", 
    url: "/yourURL", 
    dataType: "json", 
    data: "{}", 
    contentType: "application/json; charset=utf-8", 
    success: function(data) { 
     edata = $(data).find("string").text(); 
     alert(edata); 
    }, 
    error: function(e){ 
       alert('err'); 
    } 
})