Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. JSON is a syntax to store and exchange the data. JSON is a text, written with JavaScript object notation.

Exchanging data

JSON.stringify()- Send

JSON.parse() - Receive

Data Format

{ "name":"Sakthi", "Designation":"Software Engineer", "Salary":10000 };

ASP page (or) HTML
  1. <form id="form2" runat="server">
  2. <div>
  3. <script>
  4. debugger;
  5. var obj, parameter, xmlhttp, _Obj, x, result = "";
  6. obj = {
  7. "Designation": "Software",
  8. "salary": 10000
  9. }; // WHERE CONDITION
  10. dbParam = JSON.stringify(obj); // SEND PARAMETERS
  11. xmlhttp = new XMLHttpRequest();
  12. xmlhttp.onreadystatechange = function() {
  13. if (this.readyState == 4 && this.status == 200) {
  14. _Obj = JSON.parse(this.responseText); // RECEIVE
  15. result += "<table border='1'>"
  16. for (x in _Obj) {
  17. result += "<tr><td>" + _Obj[x].val + "</td></tr>";
  18. }
  19. result += "</table>"
  20. document.getElementById("demo").innerHTML = result;
  21. }
  22. };
  23. xmlhttp.open("POST", "./ReadTable.asmx/getdata", true); //METHOD POST–WEBSERVICE PAGE
  24. xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  25. xmlhttp.send("x=" + parameter);
  26. </script>
  27. <p id="demo"></p>
  28. </div>
  29. </form>

NOTE

Webservice Name ReadTable.asmx

Method Name getdata

ReadTable.cs
  1. [WebMethod]
  2. public void getdata(string x) {
  3. JavaScriptSerializer j = new JavaScriptSerializer();
  4. string json = new StreamReader(Context.Request.InputStream).ReadToEnd();
  5. Dictionary < string, string > sData = j.Deserialize < Dictionary < string, string >> (x);
  6. string Designation = sData["Designation"].ToString();
  7. String Salary = sData["Salary"].ToString();
  8. List < UserList > c = new List < UserList > ();
  9. SqlConnection con = new SqlConnection("");
  10. con.Open();
  11. SqlCommand cmd = new SqlCommand("select * from TableName where Designation=@Designation and Salary=@Salary", con);
  12. cmd.Parameters.AddWithValue("@Designation", Designation);
  13. cmd.Parameters.AddWithValue("@Salary", Salary);
  14. SqlDataAdapter da = new SqlDataAdapter(cmd);
  15. DataTable dt = new DataTable();
  16. da.Fill(dt);
  17. for (int i = 0; i < dt.Rows.Count; i++) {
  18. UserList _userlist = new UserList();
  19. _userlist.val = dt.Rows[i][0].ToString();...c.Add(_userList);
  20. }
  21. JavaScriptSerializer j2 = new JavaScriptSerializer();
  22. Context.Response.Write(j2.Serialize(c));
  23. }

USERLIST CLASS FILE

  1. class UserList {
  2. public string val {
  3. get;
  4. set;
  5. }
  6. public string val2 {
  7. get;
  8. set;
  9. }
  10. public string val3 {
  11. get;
  12. set;
  13. }...
  14. }