Get Data Using Web Services and JSON

  1. <div>  
  2.         <input id="Button1" type="button" value="Search" />  
  3.         <div id = "results"></div>  
  4.     </div> 
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>  
  2.     <script type="text/javascript">  
  3.         $("#Button1").live("click", function () {  
  4.             $.ajax({  
  5.                 type: "POST",  
  6.                 url: 'myServices.asmx/getITEM',                  
  7.                 dataType: "json",  
  8.                 success: function (response) {  
  9.                     console.log(response);                     
  10.                     var html = "";  
  11.                     $.each(response, function () {  
  12.                         html += "<span>COL1: " + this.COL1 + " COL2: " + this.COL2 + "</span><br />";  
  13.                     });  
  14.                     $("#results").html(html == "" ? "No results" : html);  
  15.                 },  
  16.                 error: function (response) {  
  17.                     console.log(response);  
  18.                 }  
  19.             });  
  20.         });  
  21.     </script> 


  1. [WebMethod]  
  2.         public void getITEM()  
  3.         {  
  4.             List<object> ITEM = new List<object>();  
  5.             using (SqlConnection conn = new SqlConnection())  
  6.             {  
  7.                 conn.ConnectionString = "Data source=xxxxx; initial catalog=xxxxx; user id=xxxx; password=xxxxx;";  
  8.                 using (SqlCommand cmd = new SqlCommand())  
  9.                 {  
  10.                     cmd.CommandText = "SELECT COL1, COL2, COL3, COL4 FROM TABLE";  
  11.                       
  12.                     cmd.Connection = conn;  
  13.                     conn.Open();  
  14.                     using (SqlDataReader sdr = cmd.ExecuteReader())  
  15.                     {  
  16.                         while (sdr.Read())  
  17.                         {  
  18.                             ITEM.Add(new  
  19.                             {  
  20.                                 COL1 = sdr["COL1"],  
  21.                                 COL2 = sdr["COL2"],  
  22.                                 COL3 = sdr["COL3"],  
  23.                                 COL4 = sdr["COL4"]  
  24.                             });  
  25.                         }  
  26.                     }  
  27.                     conn.Close();  
  28.                 }  
  29.                 System.Web.Script.Serialization.JavaScriptSerializer JS = new JavaScriptSerializer();  
  30.   
  31.                 Context.Response.Write(JS.Serialize(ITEM));  
  32.             }  
  33.         }