在ajax交互中,我们从服务器端返回的数据类型有xml,html,script,json,jsonp,text,本文以json为例,讲述了在前台如何利用jquery遍历json的两种数据结构:“名称/值”对的集合,值的有序列表,以及值的有序列表里面包含“名称/值”对的集合,在服务器端,我们采用的Json.NET来序列化arraylist,hashTable,list<>等数据结构。

     在开始之前,我们需要下载Json.net,下载完成后,在网站中添加引用,打开下载的文件夹,如果是.net2.0以上的版本,使用DoNet文件夹下的Newtonsoft.Json.dll,如果是2.0的版本,使用DotNet20文件下的Newtonsoft.Json.dll,然后在使用的页面导入其命名空间 using Newtonsoft.Json;

     准备工作完毕后,下面开始演示,首先添加webService文件 命名为ProductService.asmx,然后取消对[System.Web.Script.Services.ScriptService] 的注释

   1、遍历 “名称/值”对的集合

ProductService.asmx 添加 getProductInfoToJson方法

[WebMethod]
   public string getProductInfoToJson(int productID)
    {
        SQLCMD = new SqlCommand("select id,name,price from dbo.productTest where id=@id", SQLConnect);
        SQLCMD.CommandType = System.Data.CommandType.Text;

        SQLCMD.Parameters.AddWithValue("@id", productID);

        SQLConnect.Open();
        SqlDataReader reader = SQLCMD.ExecuteReader();
        Hashtable HTresult = new Hashtable();
        while (reader.Read())
        {
            HTresult.Add("id", reader["id"]);
            HTresult.Add("name", reader["name"]);
            HTresult.Add("price", reader["price"]);
        }
        reader.Close();
        SQLConnect.Close();
        return JsonConvert.SerializeObject(HTresult);
    }
前台
$("#ShowInfo").click(function () {
            var selectValue = $("#DropDownListCourseID").val();
            $.ajax({
                type: "POST",
                url: "ProductService.asmx/getProductInfoToJson",
                data: "{productID:" + selectValue + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var result = jQuery.parseJSON(msg.d);
                    $("#resultInfo").append(result.id + result.name + result.price+"<br/>");
                }
            });
        });
 
2、遍历 值的有序列表
ProductService.asmx 添加 GetProductList方法
[WebMethod]
    public string GetProductList(string KeyWord) {

        SQLCMD = new SqlCommand("getProductList", SQLConnect);
        SQLCMD.CommandType = CommandType.StoredProcedure;

        SQLCMD.Parameters.Add(new SqlParameter("@nameKeyWords", SqlDbType.NVarChar, 30));
        SQLCMD.Parameters["@nameKeyWords"].Value = KeyWord;

        SQLConnect.Open();
        SqlDataReader reader = SQLCMD.ExecuteReader();
        ArrayList ProductList = new ArrayList();
        while (reader.Read())
        {
            ProductList.Add(reader["name"].ToString());
        }
          
          reader.Close();
          SQLConnect.Close();
        if (ProductList.Count > 0)
        {
            return JsonConvert.SerializeObject(ProductList);
        }
        else
        {
            return "";
        }
    }
前台:
var suggestList = $('<ul class="autocomplete"</ul>').hide().insertAfter("#search #search-text");

        $("#search-text").keyup(function () {
            var textString = "{KeyWord:'" + $("#search #search-text").attr("value") + "'}"

            $.ajax({
                type: "POST",
                url: "ProductService.asmx/GetProductList",
                data: textString,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    suggestList.empty();
                    var objData = jQuery.parseJSON(data.d);
                    $.each(objData, function (index, term) {
                        $("<li></li>").text(term).appendTo(suggestList);
                    });
                    suggestList.show();
                }
            });
        });
3、遍历 值的有序列表里面包含“名称/值”对的集合
ProductService.asmx 添加 GetBrandNameByKeyword方法
[WebMethod]
    public string GetBrandNameByKeyword(string Keyword)
    {
        SQLCMD = new SqlCommand("BrandInfo_Get_BrandName_UserInputKeyWord", SQLConnect);
        SQLCMD.CommandType = CommandType.StoredProcedure;

        SQLCMD.Parameters.Add(new SqlParameter("@KeyWord",SqlDbType.NVarChar,10));
        SQLCMD.Parameters["@KeyWord"].Value = Keyword;

        Hashtable BrandNameInfo;
        List<Hashtable> BrandNameInfoCollection = new List<Hashtable>();
        SQLConnect.Open();

        using (SqlDataReader reader = SQLCMD.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    BrandNameInfo = new Hashtable();
                    BrandNameInfo.Add("BrandName", reader["BrandName"].ToString());
                    BrandNameInfo.Add("BrandChineseName", reader["BrandChineseName"].ToString());
                    BrandNameInfo.Add("nameAbbreviation", reader["nameAbbreviation"].ToString());
                    BrandNameInfoCollection.Add(BrandNameInfo);
                }
                SQLConnect.Close();
                return JsonConvert.SerializeObject(BrandNameInfoCollection);
            }
            else
            {
                SQLConnect.Close();
                return null;
            }
        }
    }
前台
$.ajax({
                type: "POST",
                url: "ProductService.asmx/GetReceiverAddressInfo",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var resultCollection = jQuery.parseJSON(msg.d);
                    $.each(resultCollection, function (index, item) {
                        var AddressInfo = [
                        '<input type="radio" name="ReceiveAddress" class="address" value="', item.id, '"/> <label class="vtip" title="<font size=3><b>收件人:</b> ', item.ReceiverName, '</br><b>联系号码:</b> ', item.ReceiverPhoneNo, '</br><b>详细地址:</b> ', item.DetailsAddress, '</font>">', item.NoticeWords, '</label></br>'
                        ].join('');
});
}
});
 
   在1.41中,jquery添加了 jQuery.parseJSON( json ) 的方法,该方法的定义是Takes a well-formed JSON string and returns the resulting JavaScript object. 就是接受一个格式良好的JSON字符串,返回一个Javascript对象。
这大大方便了我们在前台对服务器端生成的Json字符串的处理.
   好了,关于Jquery遍历Json两种数据结构的介绍就到这里