Saturday, May 31, 2008

Using jQuery to directly call ASP.NET AJAX page methods

 

   1: public partial class _Default : Page 
   2: {
   3:   [WebMethod]
   4:   public static string GetDate()
   5:   {
   6:     return DateTime.Now.ToString();
   7:   }
   8: }
   1: <html>
   2: <head>
   3:   <title>Calling a page method with jQuery</title>
   4:   <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   1:  
   2:   <script type="text/javascript" src="Default.js">
</script>
   5: </head>
   6: <body>
   7:   <div id="Result">Click here for the time.</div>
   8: </body>
   9: </html>
   1: $(document).ready(function() {
   2:   // Add the page method call as an onclick handler for the div.
   3:   $("#Result").click(function() {
   4:     $.ajax({
   5:       type: "POST",
   6:       url: "Default.aspx/GetDate",
   7:       beforeSend: function(xhr) {
   8:         xhr.setRequestHeader("Content-type", 
   9:                              "application/json; charset=utf-8");
  10:       },
  11:       dataType: "json",
  12:       success: function(msg) {
  13:         // Replace the div's content with the page method's return.
  14:         $("#Result").text(msg.d);
  15:       }
  16:     });
  17:   });
  18: });

 

Source

No comments:

Post a Comment