JSON的数据格式:{"xx":"xx1","yy":[{"yy1":"yyy1"},{"yy2":"yyy2"}]}

后台部分:(合成JSON数据格式)

//这是获取根目录
public string getRootTree()
{

using(SqlDataReader dr=SqlHelper.ExecuteReader(conn,System.Data.CommandType.Text,"select * from MMenu where MParentID=0"))
{
sb.Append("{""region"":[");
while(dr.Read())
{
sb.Append("{""");
sb.Append("MID");
sb.Append(""":""");
sb.Append(dr["MID"].ToString());
sb.Append(""",""");
sb.Append("MName");
sb.Append(""":""");
sb.Append(dr["MName"].ToString());
sb.Append(""",""");
sb.Append("MParentID");
sb.Append(""":""");
sb.Append(dr["MParentID"].ToString());
sb.Append("""},");
}
sb.Append("]");
return sb.ToString().Substring(0,sb.ToString().Length-2)+"]}";
}

//根据ID获取下级的数据

public string getSubTree(int MID)
{
using(SqlDataReader dr=SqlHelper.ExecuteReader(conn,System.Data.CommandType.Text,"select * from MMenu where MParentID="+MID))
{
sb.Append("{""region"":[");
while(dr.Read())
{
sb.Append("{""");
sb.Append("MID");
sb.Append(""":""");
sb.Append(dr["MID"].ToString());
sb.Append(""",""");
sb.Append("MName");
sb.Append(""":""");
sb.Append(dr["MName"].ToString());
sb.Append(""",""");
sb.Append("MParentID");
sb.Append(""":""");
sb.Append(dr["MParentID"].ToString());
sb.Append("""},");
}
sb.Append("]");
return sb.ToString().Substring(0,sb.ToString().Length-2)+"]}";
}
}

前台部分:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html>
<head>
<title>select</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
<script src=js/prototype-1.4.0.js></script>
<script>
function getJSON()
{
var myoptions={
parameters:"",
method:"get",
onSuccess:function(res){
var myData=eval("("+res.responseText+")");
myData.region.each(function(xx){
$("root").options.add(new Option(xx.MName,xx.MID));
}
);

}
}
new Ajax.Request("jsonSelect.aspx?action=root&s"+Math.random(),myoptions);
}

function getSub(id)
{
var myoptions={
parameters:"subID="+id,
method:"get",
onSuccess:function(res){
var myData=eval("("+res.responseText+")");
$("sub").options.length=1;
myData.region.each(function(xx){

$("sub").options.add(new Option(xx.MName,xx.MID));
}
);
}
}
new Ajax.Request("jsonSelect.aspx?action=sub&s"+Math.random(),myoptions);
}
</script>
</head>
<body onload=getJSON()>

<form id="Form1" method="post" runat="server">
<select name="a" id="root" onChange="getSub(this.value)">
<option value="" selected>-----请选择类别-----</option>

</select>
<select name="a" id="sub" onChange="getSub(this.value)">
<option value="" selected>-----请选择类别-----</option>

</select>
</form>

</body>
</html>
posted on 2008-10-18 22:37  冷火  阅读(312)  评论(0编辑  收藏  举报