生成下拉列表

1. GetClassData.html

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title></title>
 6     <script type="text/javascript">
 7         window.onload = function () {
 8             //向服务器请求时间
 9             //1. 创建异步对象(小浏览器)
10             var xhr = new XMLHttpRequest();
11             //2. 设置参数(请求方式,请求页面,是否异步)
12             xhr.open("get", "GetClassData.ashx?type=1", true);
13             //3. 让get请求不从浏览器获取缓存数据
14             xhr.setRequestHeader("If-Modified-Since", "0");
15             //4. 设置回掉函数
16             xhr.onreadystatechange = function () {
17                 if (xhr.readyState == 4 && xhr.status == 200) {
18                     var res = xhr.responseText;
19                     //alert(res);
20                     //转换成json数组
21                     var jsonArr = JSON.parse(res);
22                     loadSel("selList", jsonArr, "id", "name");
23                 }
24             };
25             //4. 发送异步请求
26             xhr.send(null);
27         };
28         function loadSel(selId, dataArr, valueFiele, textField) {
29             var selObj = document.getElementById(selId);
30             //清空原下拉框中的数据,避免重复添加
31             selObj.options.length = 0;
32             for (var i = 0; i < dataArr.length; i++) {
33                 var item = dataArr[i];
34                 var opt = new Option(item[textField], item[valueFiele]);
35                 selObj.options.add(opt);
36             }
37         }
38     </script>
39 </head>
40 <body>
41     <select id="selList">
42         <option>哈哈</option>
43     </select>
44 </body>
45 </html>
View Code

2. GetClassData.ashx

 1 <%@ WebHandler Language="C#" Class="GetClassData" %>
 2 
 3 using System;
 4 using System.Web;
 5 using System.Data;
 6 using System.Text;
 7 
 8 public class GetClassData : IHttpHandler
 9 {
10 
11     public void ProcessRequest(HttpContext context)
12     {
13         string strType = context.Request.QueryString["type"];
14         switch (strType)
15         {
16             case "1":
17                 LoadClassData(context);
18                 break;
19         }
20     }
21 
22     void LoadClassData(HttpContext context)
23     {
24         DataTable dt = SqlHelper.GetDataTable("select * from Classes where CIsDel=0");
25         StringBuilder sb = new StringBuilder("[", 200);
26         foreach (DataRow dr in dt.Rows)
27         {
28             sb.Append("{\"id\":\"" + dr["CID"] + "\",\"name\":\"" + dr["CName"] + "\"},");
29         }
30         context.Response.Write(sb.Remove(sb.Length - 1, 1).ToString() + "]");
31     }
32 
33     public bool IsReusable
34     {
35         get
36         {
37             return false;
38         }
39     }
40 
41 }
View Code

 

posted @ 2014-11-13 13:09  叫我霍啊啊啊  阅读(145)  评论(0编辑  收藏  举报