This code snippet is for get Data Using Web Services and JSON.
<div>
<input id="Button1" type="button" value="Search" />
<div id = "results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$("#Button1").live("click", function () {
$.ajax({
type: "POST",
url: 'myServices.asmx/getITEM',
dataType: "json",
success: function (response) {
console.log(response);
var html = "";
$.each(response, function () {
html += "<span>COL1: " + this.COL1 + " COL2: " + this.COL2 + "</span><br />";
});
$("#results").html(html == "" ? "No results" : html);
},
error: function (response) {
console.log(response);
}
});
});
</script>
[WebMethod]
public void getITEM()
{
List<object> ITEM = new List<object>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data source=xxxxx; initial catalog=xxxxx; user id=xxxx; password=xxxxx;";
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT COL1, COL2, COL3, COL4 FROM TABLE";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ITEM.Add(new
{
COL1 = sdr["COL1"],
COL2 = sdr["COL2"],
COL3 = sdr["COL3"],
COL4 = sdr["COL4"]
});
}
}
conn.Close();
}
System.Web.Script.Serialization.JavaScriptSerializer JS = new JavaScriptSerializer();
Context.Response.Write(JS.Serialize(ITEM));
}
}