关于AJAX+HTML5+ASHX进行全静态页面的数据交互

及时总结项目中使用到的知识,知识在于积累。

1.HTML代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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">你要找的人:‘;
$.each(data.student, function(commentIndex, comment){
html += ‘<h3>‘ + comment[‘name‘]
+ ‘</h6></div>‘;
});

$(‘#divinfo‘).html(html);
}
else {
$(‘#divinfo‘).text("error");
}
}
});
});
});
</script>
</head>
<body>
编号:<input id="txtID" type="text" /><br />
<input id="btnTest" type="button" value="找人" /><br />
<div id="divinfo"></div>
</body>
</html>

2.ashx代码

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "json";
string id = context.Request["id"];
DataSet ds = new DataSet();
using (DataTable dt = new DataTable("students"))
{
//创建列
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);

//添加数据到DataTable
DataRow dr = dt.NewRow();
if (id == "0")
{
dr["name"] = "张三";
dr["sex"] = "男";
dr["tel"] = 54531;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["name"] = "李四";
dr["sex"] = "男";
dr["tel"] = 5731;
dt.Rows.Add(dr);
}
if (id == "1")
{
dr = dt.NewRow();
dr["name"] = "李四";
dr["sex"] = "男";
dr["tel"] = 5731;
dt.Rows.Add(dr);
}
if (id == "2")
{
dr = dt.NewRow();

dr["name"] = "王五";
dr["sex"] = "女";
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();
jsonBuilder.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)//表示有数据,则需要删除最后的一个 ,
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}

关于AJAX+HTML5+ASHX进行全静态页面的数据交互,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。