顯示具有 json 標籤的文章。 顯示所有文章
顯示具有 json 標籤的文章。 顯示所有文章

2012年2月3日 星期五

ASP.NET WebService 回傳 json 格式

1. 撰寫 jQuery 取得 json 字串
$(document).ready(function () {
    $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Default.aspx/GetData",
            data: '{ Id: "' + $("#Id").val() + '" }',
            dataType: "json",
            success: function (msg) {
            var c = eval(msg.d);

            for (var i = 0; i < c.length; i++) {
                 alert("Id=" + c[i][0] + "/Name=" + c[i][1] );
            }
        }
    });
});

 
2. 撰寫 WebService 程式
#region "*-----------------------------------WebService-----------------------------------*"
[System.Web.Services.WebMethod]
public static string GetData() {
string strJSON = "";

System.Collections.Specialized.NameValueCollection arrList = new System.Collections.Specialized.NameValueCollection();

arrList.Add("01","Jerry");
arrList.Add("02","Marry");
arrList.Add("03","Tom");

string[][] JaggedArray = new string[arrList.Count][];

int i = 0;

foreach (string key in arrList) {
    JaggedArray[i] = new string[] { key, arrList[key] };
    i = i + 1;
}

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

strJSON = js.Serialize(JaggedArray);

return strJSON;

}

#endregion



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>

2011年9月17日 星期六

JSON 資料會 cache 的問題

練習了一個功能,用 PHP 去讀後端資料庫,再轉成 JSON 的格式,直接使用 JQuery 轉成 table
本來一切還正常,今天突然資料都不會即時更新了,好像把 ie 關掉重開資料才會跑出來。

試了一下,把 cache 關掉好像就正常了

兩種寫法:

$.ajax({
        url: "action/dictumQuery.php",
        cache: false,
        type: "GET",
        dataType: "json",
        success: function (data) {
var tblRow = "";
$.each(data.tabledata, function(i,tbl){
tblRow += ""
+""+tbl.id+""
+""+tbl.dictum+""
+""+tbl.times+""
+""+tbl.crttime+""
+""

});
$('#userdata tbody').replaceWith( tblRow );
        },
        error: function () {
            alert("ERROR!!!");
        }
    });





$.getJSON(
"action/dictumQuery.php",
function(data){
$.each(data.tabledata, function(i,tbl){
var tblRow =
""
+""+tbl.id+""
+""+tbl.dictum+""
+""+tbl.times+""
+""+tbl.crttime+""
+""
$(tblRow).appendTo("#userdata tbody");
});
$.ajaxSetup({ cache: false });
}
);

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. 最後結果如下: