Summarize the knowledge that is used in the project in time, knowledge is accumulated.
1.HTML Code
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<script src= "Js/jquery-1.7.1.min.js" "type=" Text/javascript "></script>
<script type= "Text/javascript" >
$ (function () {
$ (' #btnTest '). Click (function () {
var html = "";
$.ajax ({
Type: "Post",
URL: "Datahandle.ashx",
Data: {id:$ ("#txtID"). Val ()},
DataType: "JSON",
Success:function (data) {
if (data.student[0].name! = ") {
$ (' #divinfo '). Text (data.student[0].name);
HTML + = ' <br><div class= "comment" > The person you're looking for: ';
$.each (data.student, function (Commentindex, comment) {
HTML + = ' + ' });
$ (' #divinfo '). HTML (HTML);
}
else {
$ (' #divinfo '). Text ("error");
}
}
});
});
});
</script>
<body>
Ref.: <input id= "txtID" type= "text"/><br/>
<input id= "btntest" type= "button" value= "Find Someone"/><br/>
<div id= "Divinfo" ></div>
</body>
2.ASHX Code
public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "JSON";
String id = context. request["id"];
DataSet ds = new DataSet ();
using (DataTable dt = new DataTable ("Students"))
{
Create columns
DataColumn DTC = new DataColumn ("name", typeof (String));
Dt. Columns.Add (DTC);
DTC = new DataColumn ("Sex", typeof (String));
Dt. Columns.Add (DTC);
DTC = new DataColumn ("Tel", typeof (Int32));
Dt. Columns.Add (DTC);
Adding data to a DataTable
DataRow dr = dt. NewRow ();
if (id = = "0")
{
dr["name"] = "Zhang San";
dr["Sex" = "male";
dr["tel"] = 54531;
Dt. Rows.Add (DR);
Dr = dt. NewRow ();
dr["name"] = "John Doe";
dr["Sex" = "male";
dr["tel"] = 5731;
Dt. Rows.Add (DR);
}
if (id = = "1")
{
Dr = dt. NewRow ();
dr["name"] = "John Doe";
dr["Sex" = "male";
dr["tel"] = 5731;
Dt. Rows.Add (DR);
}
if (id = = "2")
{
Dr = dt. NewRow ();
dr["name"] = "Harry";
dr["Sex" = "female";
dr["tel"] = 5868451;
Dt. Rows.Add (DR);
}
Ds. Tables.add (DT);
}
String jsontable = "Student";
String Strre = Tabletojson (ds. Tables[0], jsontable);
Context. Response.Write (Strre);
}
public string Tabletojson (DataTable dt, string jsonname)
{
var jsonbuilder = new StringBuilder ();
Jsonbuild Er. Append ("{\" ");
//jsonbuilder.append (dt. Tablename.tostring ());
Jsonbuilder.append (jsonname + "\": ");
Jsonbuilder.append ("[");
for (int i = 0; i < dt. Rows.Count; i++)
{
Jsonbuilder.append ("{");
for (int j = 0; j < dt. Columns.count; J + +)
{
Jsonbuilder.append ("\" ");
Jsonbuilder.append (dt. COLUMNS[J]. ColumnName);
Jsonbuilder.append ("\": \ "");
Jsonbuilder.append (dt. ROWS[I][J]. ToString ());
Jsonbuilder.append ("\", ");
}
Jsonbuilder.remove (jsonbuilder.length-1, 1);
Jsonbuilder.append ("},");
}
if (dt. Rows.Count > 0)//indicates that there is data, you need to delete the last one,
Jsonbuilder.remove (jsonbuilder.length-1, 1);
Jsonbuilder.append ("]");
Jsonbuilder.append ("}");
return jsonbuilder.tostring ();
}