两张表:
test test1
uid uname uid tid uname
1 aaa 1 1 第一个1
2 bbb 2 1 第一个2
3 ccc 3 2 第二个
4 ddd 4 3 第三个
我运行a.aspx后,dropdownlist2没有反应,是不是我哪块SQL查询写错了,因为我用别的表好用
a.aspx中HTML的代码:
<script type="text/javascript">
function load(state)
{
var drp2 = document.getElementById("DropDownList2");
for (i = drp2.length; i >= 0; i--)
{
drp2.options.remove(i);
}
var oHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
var oDoc = new ActiveXObject("MSXML2.DOMDocument");
oHttpReq.open("POST", "b.aspx?state="+state, false);
oHttpReq.send("");
result = oHttpReq.responseText;
oDoc.loadXML(result);
items1 = oDoc.selectNodes("//NewDataSet/Table/tid"); //这个是用DataSet里的数据
items2 = oDoc.selectNodes("//NewDataSet/Table/uname"); //为DropDownList2要显示的字段
var itemsLength=items1.length;
for(i=0;i<itemsLength;i++)
//将小类的类名和编号赋予DropDownList2
{
var newOption = document.createElement("OPTION");
newOption.text=items2[i].text;
newOption.value=items1[i].text;
drp2.options.add(newOption);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
<asp:DropDownList id="DropDownList2" runat="server"></asp:DropDownList>
</div>
</form>
</body>
----------------------------------------------------------------------------------
a.aspx.cs的代码
SqlConnection con = new SqlConnection("server=.;database=pubs;uid=sa");
string sql = "select * from test";
SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
da.Fill(ds);
this.DropDownList1.DataSource = ds.Tables[0].DefaultView;
this.DropDownList1.DataTextField = "uname";
this.DropDownList1.DataValueField = "uid";
this.DropDownList1.DataBind();
// 这里是绑定客户端事件,当第一个DropDownList的选项改变时激发下面的事件onchange,这个事件将调用一个客户端方法load()
this.DropDownList1.Attributes.Add("onchange", "load(this.options[this.selectedIndex].value)");
-------------------------------------------------------------------------------------------------
b.aspx。cs的代码
string shengNo = Request["state"].ToString();
SqlConnection con = new SqlConnection("server=.;database=pubs;uid=sa");
//这是DropDownList2要显示的字段
string sql = "select uid,uname from test1 where tid='" + shengNo + "'";
SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
writer.IndentChar = ' ';
writer.WriteStartDocument();
ds.WriteXml(writer);
writer.Flush();
Response.End();
writer.Close();