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



沒有留言:

張貼留言