我數據放在returndata.aspx的datatable中,第一次執行是可以的,當選擇dropdownlist中不同的option會返回不同的信息,但是當遍歷完datatable中的所有rows之後,dropdownlist的onchange事件失效了,獲取的內容不再更新。
1. Defalut.aspx <script type="text/javascript" language="javascript">
var xmlhttp = null;
function GETXMLHttpRequest() {
if (document.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function getInfo(value) {
GETXMLHttpRequest();
var url = "ReturnData.aspx?id=" + value;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
}
</script>
<asp:DropDownList ID="DropDownList1" runat="server" onchange="getInfo(this.value)">
</asp:DropDownList> //dropdownlist的onchange事件調用上面的js
Default.aspx的後台代碼 private void ShowData()
{
string sql = "select * from stu";
DataTable dt = SqlHelper.ExecuteQurly(sql);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "sname";
DropDownList1.DataValueField = "sid";
DropDownList1.DataBind();
}//從數據庫中綁定dropdownlist的內容
ReturnData.aspx(default.aspx獲取數據的頁面) 後台代碼 private void getData()
{
if (Request.QueryString["id"] == null)
return;
string id = Request.QueryString["id"].ToString();
if (id == "")
return;
string sql = string.Format("select * from stu where sid={0}", id);
DataTable dt = SQLHelper.SqlHelper.ExecuteQurly(sql);
Response.Write("<table><tr><td>學號</td><td>姓名</td><td>性別</td></tr>");
if (dt.Rows.Count <= 0)
return;
for (int i = 0; i < dt.Rows.Count; i++)
{
string sql2 = string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
dt.Rows[i][0].ToString(),
dt.Rows[i][1].ToString(),
dt.Rows[i][2].ToString());
Response.Write(sql2);
}
Response.Write("</table>");
Response.End();
}
function GETXMLHttpRequest() {
if (window.XMLHttpRequest) { //判斷是出現錯誤了
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}