在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 "";
}
}
前台:
代码如下: