前台頁面
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>根據班級獲取學員下拉框數據</title>
<script type="text/javascript" >
//1.頁面加載完畢後創建異步對象 請求班級數據
window.onload = function () {
//1.1創建異步對象
var xhr = new XMLHttpRequest();
//1.2設置參數
xhr.open("get", "GetData.ashx?type=1", true);
//1.3設置不使用浏覽器緩存
xhr.setRequestHeader("If-Modified-Since", "0");
//1.4設置回調函數
xhr.onreadystatechange = function () {
//當完全接收完響應報文後,並且 響應狀態碼為200的時候
if (xhr.readyState == 4 && xhr.status == 200) {
//[{'id':'1','name':'1班'},{'id':'2','name':'2班'},{'id':'3','name':'3班'}]
var res = xhr.responseText;//獲取響應報文體內容
//===============將數據轉成js數組============
//var resJson = eval(res);//第一種轉換方法
//標准json格式[{"id":"1","name":"1班"},{"id":"2","name":"2班"}]
//將 接收到的 json字符串 轉換成 json對象
//注意:json其實是一種 數據傳輸的 格式(json格式滿足js字面量表示法語法) 浏覽器和服務器端 實際 不存在 所謂的 json 對象 其實就是js對象
var jsonArr = JSON.parse(res);//第二種轉換方法 注意:用這種格式轉換的時候屬性名必須用雙引號
loadSel("selClass", jsonArr, "id", "name");
//========================================
//alert(resJson2.length);
//document.getElementById("selClass").innerHTML = res;
}
}
//1.5發送異步請求
xhr.send(null);
};
/*
生成下拉框選項
*/
function loadSel(selId, dataArr, valueField, textField) {
//根據id獲取下拉框
var selObj = document.getElementById(selId);
//清空下拉框選項
selObj.options.length = 0;
//遍歷數據數組
for (var i = 0; i < dataArr.length; i++) {
//取出數據元素
var item = dataArr[i]; //item.id item.name方式來訪問 或者item["id"] item["name"] 來訪問
//創建 下拉框選項 對象
var opt = new Option(item[textField], item[valueField]);
//添加到下拉框中
selObj.options.add(opt);
}
}
</script>
</head>
<body>
<center id="centerCon">
班級:<select id="selClass"><option>哇哈哈哈</option></select>
學生:<select id="selStu"></select>
</center>
</body>
本欄目