项目中用到通过ajax请求数据然后给select赋值,由于经常遇到类似的代码,在这里把整个过程记录一下。
首选发出ajax请求如下:
<script type="text/javascript">
$(function () {
$.post("../../tools/yiliaofuwu.ashx", { "action": "one" }, function (data) {
var table = data.r;
$("#in_class1").empty();//首先清空select现在有的内容
$("#in_class1").append("<option selected='selected' value=0>请选择..</option>");
for (var i = 0; i < table.length; i++) {
var item = table[i];
// var option = $("<option value="+item.id+">"+item.name+"</option>");
$("#in_class1").append("<option value=" + item.Id + ">" + item.Name + "</option>");
}
//返回的是json格式的数据
}, "json"); });
</script>
后台逻辑处理的代码如下:
namespace EazyCMS.Web.tools
{
/// <summary>
/// yiliaofuwu 的摘要说明
/// </summary>
public class yiliaofuwu : IHttpHandler
{
private string sql = string.Empty;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request["action"];
switch (action)
{
case "one": //医疗服务第一类
check_one(context);
break;
} }
private void check_one(HttpContext context)
{
sql = "select * from dbo.eazy_yitype where parentid=0";
DataTable dt = DbHelperSQL.Query(sql).Tables[0];
results results = new results();
results.r = new result[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
results.r[i] = new result() { Id = dt.Rows[i]["id"].ToString(), Name = dt.Rows[i]["typename"].ToString() };
}
context.Response.Write(new JavaScriptSerializer().Serialize(results)); }
class results
{
public result[] r { get; set; }
}
class result
{
public string Id { get; set; }
public string Name { get; set; }
}
public bool IsReusable
{
get
{
return false;
}
}
}
}