2011年9月9日 星期五

使用 JQuery 取得 json 的值

1. 建立一個 ASP.NET的空網站,產生 Default.aspx, Service.ashx(範型處理程式)

2. 我預設 json 的格式為:
{"student":[{ "name": "Marry", "height": "154", "weight": "45" },{ "name": "Tom", "height": "170", "weight": "60" }]}

3.  在 Service.ashx 撰寫程式如下:     public void ProcessRequest (HttpContext context) {
        //接收參數
        string name = context.Request.Params["name"];
        context.Response.ContentType = "text/plain";
        //組成json格式
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.AppendLine("{\"student\":[{ \"name\": \"" + name + "\", \"height\": \"154\", \"weight\": \"45\" },{ \"name\": \"Tom\", \"height\": \"170\", \"weight\": \"60\" }]}");
        //回傳json字串
        context.Response.Write(builder.ToString());
    }

4. 在 Default.aspx 撰寫程式如下:

$.ajax({
            url: "Service.ashx",
            type: "GET",
            data: {"name":"Jacky"},
            dataType: "json",
            success: function (data) {
                $.each(data.student, function () {
                    document.write("姓名=" + this.name + ";身高=" + this.height + ";體重=" + this.weight + "
");
                });
            },
            error: function () {
                alert("ERROR!!!");
            }
        });



5. 最後結果如下:




沒有留言:

張貼留言