通過(guò)Jquery遍歷Json的兩種數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn)代碼
更新時(shí)間:2011年01月19日 23:58:07 作者:
在ajax交互中,我們從服務(wù)器端返回的數(shù)據(jù)類(lèi)型有xml,html,script,json,jsonp,text,本文以json為例,講述了在前臺(tái)如何利用jquery遍歷json的兩種數(shù)據(jù)結(jié)構(gòu)
在ajax交互中,我們從服務(wù)器端返回的數(shù)據(jù)類(lèi)型有xml,html,script,json,jsonp,text,本文以json為例,講述了在前臺(tái)如何利用jquery遍歷json的兩種數(shù)據(jù)結(jié)構(gòu):“名稱(chēng)/值”對(duì)的集合,值的有序列表,以及值的有序列表里面包含“名稱(chēng)/值”對(duì)的集合,在服務(wù)器端,我們采用的Json.NET來(lái)序列化arraylist,hashTable,list<>等數(shù)據(jù)結(jié)構(gòu)。
在開(kāi)始之前,我們需要下載Json.net,下載完成后,在網(wǎng)站中添加引用,打開(kāi)下載的文件夾,如果是.net2.0以上的版本,使用DoNet文件夾下的Newtonsoft.Json.dll,如果是2.0的版本,使用DotNet20文件下的Newtonsoft.Json.dll,然后在使用的頁(yè)面導(dǎo)入其命名空間 using Newtonsoft.Json;
準(zhǔn)備工作完畢后,下面開(kāi)始演示,首先添加webService文件 命名為ProductService.asmx,然后取消對(duì)[System.Web.Script.Services.ScriptService] 的注釋。
1、遍歷 “名稱(chēng)/值”對(duì)的集合
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);
}
前臺(tái)
$("#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 "";
}
}
前臺(tái):
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、遍歷 值的有序列表里面包含“名稱(chēng)/值”對(duì)的集合
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;
}
}
}
前臺(tái)
$.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>聯(lián)系號(hào)碼:</b> ', item.ReceiverPhoneNo, '</br><b>詳細(xì)地址:</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. 就是接受一個(gè)格式良好的JSON字符串,返回一個(gè)Javascript對(duì)象。
這大大方便了我們?cè)谇芭_(tái)對(duì)服務(wù)器端生成的Json字符串的處理.
好了,關(guān)于Jquery遍歷Json兩種數(shù)據(jù)結(jié)構(gòu)的介紹就到這里
在開(kāi)始之前,我們需要下載Json.net,下載完成后,在網(wǎng)站中添加引用,打開(kāi)下載的文件夾,如果是.net2.0以上的版本,使用DoNet文件夾下的Newtonsoft.Json.dll,如果是2.0的版本,使用DotNet20文件下的Newtonsoft.Json.dll,然后在使用的頁(yè)面導(dǎo)入其命名空間 using Newtonsoft.Json;
準(zhǔn)備工作完畢后,下面開(kāi)始演示,首先添加webService文件 命名為ProductService.asmx,然后取消對(duì)[System.Web.Script.Services.ScriptService] 的注釋。
1、遍歷 “名稱(chēng)/值”對(duì)的集合
ProductService.asmx 添加 getProductInfoToJson方法
復(fù)制代碼 代碼如下:
[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);
}
前臺(tái)
復(fù)制代碼 代碼如下:
$("#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、遍歷 值的有序列表
復(fù)制代碼 代碼如下:
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 "";
}
}
前臺(tái):
復(fù)制代碼 代碼如下:
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、遍歷 值的有序列表里面包含“名稱(chēng)/值”對(duì)的集合
復(fù)制代碼 代碼如下:
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;
}
}
}
前臺(tái)
復(fù)制代碼 代碼如下:
$.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>聯(lián)系號(hào)碼:</b> ', item.ReceiverPhoneNo, '</br><b>詳細(xì)地址:</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. 就是接受一個(gè)格式良好的JSON字符串,返回一個(gè)Javascript對(duì)象。
這大大方便了我們?cè)谇芭_(tái)對(duì)服務(wù)器端生成的Json字符串的處理.
好了,關(guān)于Jquery遍歷Json兩種數(shù)據(jù)結(jié)構(gòu)的介紹就到這里
您可能感興趣的文章:
- JavaScript 處理樹(shù)數(shù)據(jù)結(jié)構(gòu)的方法示例
- javascript數(shù)據(jù)結(jié)構(gòu)之多叉樹(shù)經(jīng)典操作示例【創(chuàng)建、添加、遍歷、移除等】
- ReactJs實(shí)現(xiàn)樹(shù)形結(jié)構(gòu)的數(shù)據(jù)顯示的組件的示例
- JavaScript數(shù)據(jù)結(jié)構(gòu)之鏈表的實(shí)現(xiàn)
- JavaScript數(shù)據(jù)結(jié)構(gòu)與算法之集合(Set)
- js圖數(shù)據(jù)結(jié)構(gòu)處理 迪杰斯特拉算法代碼實(shí)例
相關(guān)文章
hover的用法及l(fā)ive的用法介紹(鼠標(biāo)懸停效果)
hover屬性在書(shū)寫(xiě)css時(shí)大家都不會(huì)陌生了吧live主要用于對(duì)動(dòng)態(tài)加載出來(lái)的元素綁定事件,下來(lái)將為大家詳細(xì)介紹下兩者的使用,感興趣的朋友可不要錯(cuò)過(guò)了哈2013-03-03
JQuery獲取與設(shè)置HTML元素的內(nèi)容或文本的實(shí)現(xiàn)代碼
使用JQuery可以非常容易地添加、獲取和改變某個(gè)HTML元素的內(nèi)容,你會(huì)為這種簡(jiǎn)便感到非常愉悅2014-06-06
jQuery實(shí)現(xiàn)的兩種簡(jiǎn)單彈窗效果示例
這篇文章主要介紹了jQuery實(shí)現(xiàn)的兩種簡(jiǎn)單彈窗效果,結(jié)合實(shí)例形式分析了jQuery實(shí)現(xiàn)淡入彈窗及滑動(dòng)彈窗的相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
使用Browserify配合jQuery進(jìn)行編程的超級(jí)指南
這篇文章主要介紹了使用Browserify配合jQuery進(jìn)行編程的超級(jí)指南,Browserify 可以讓你使用類(lèi)似于node的require()的方式來(lái)組織瀏覽器端的JavaScript代碼,需要的朋友可以參考下2015-07-07
jQuery自定義動(dòng)畫(huà)函數(shù)實(shí)例詳解(附demo源碼)
這篇文章主要介紹了jQuery自定義動(dòng)畫(huà)函數(shù)實(shí)現(xiàn)方法,形式實(shí)例分析了jQuery通過(guò)插件結(jié)合數(shù)學(xué)運(yùn)算實(shí)現(xiàn)滑塊動(dòng)畫(huà)運(yùn)動(dòng)的效果,并附完整demo源碼供讀者下載,需要的朋友可以參考下2015-12-12

