1.DataTableToJson方法:
public string DataTableToJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
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("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
if (jsonBuilder.ToString()!="")
{
jsonBuilder.Append("]");
}
return jsonBuilder.ToString();
}
使用context.Response.Write(jsonBuilder.ToString);输出字符串
2.前台<script></script>
$("#dbtn").click(function(){
var txb_name = $('#txb_changeName').val();
$.ajax({
type: "POST",
url:"Handler.ashx",
data:{name:txb_name},
beforeSend:function(){
$("#lb_tips").html("loading");
},
success: function(msg){
if(msg!="")
{
var type= eval(msg);
var str = "first";
for(var i = 0;i<type.length;i++)
{
str+="<a>"+type[i].membUser+"</a>"
}
$('#lb_tips').html(str);
}
else
{
var notfound="<h2>未找到数据</h2>";
$('#lb_tips').html(notfound);
}
}
});
});