2011年11月19日 星期六
使用 JQuery 取得 json 的值 - Binding 到下拉選單中
1. 在 BasicService.ashx 的檔案中撰寫以下程式碼,主要為了產生 json 格式的字串回傳
public class BasicService : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string _service = context.Request.Params["Service"];
string rtnflag = "";
context.Response.ContentType = "text/plain";
switch (_service) {
case "getMonth":
rtnflag = getMonth();
break;
}
//回傳json字串
context.Response.Write(rtnflag);
}
public bool IsReusable
{
get
{
return false;
}
}
public string getMonth() {
StringBuilder builder = new StringBuilder();
builder.AppendLine("{");
for (int i = 1; i <= 12; i++) {
builder.AppendLine("\"" + i.ToString().PadLeft(2, '0') + "\": \"" + i.ToString().PadLeft(2, '0') + "\"");
if (i < 12) {
builder.AppendLine(",");
}
}
builder.AppendLine("}");
return builder.ToString();
}
}
2. 在*.aspx 撰寫以下的程式碼
<script language="javascript">
$(document).ready(function () {
$.getJSON('../Services/BasicService.ashx', { Service: "getMonth" }, function (data) {
$.each(data, function (key, val) {
$("#Select3")[0].options.add(new Option(val, key));
});
});
});
</script>
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言