Home  >  Article  >  Web Front-end  >  Implementation code for traversing two Json data structures through Jquery_jquery

Implementation code for traversing two Json data structures through Jquery_jquery

WBOY
WBOYOriginal
2016-05-16 18:11:27964browse

In ajax interaction, the data types we return from the server include xml, html, script, json, jsonp, and text. This article uses json as an example to describe how to use jquery to traverse the two data structures of json in the foreground: "name/ A collection of "value" pairs, an ordered list of values, and an ordered list of values ​​containing a collection of "name/value" pairs. On the server side, we use Json.NET to serialize arraylist, hashTable, list<> and other data structures.
Before we start, we need to download Json.net. After the download is completed, add a reference to the website and open the downloaded folder. If it is .net2.0 or above, use Newtonsoft.Json in the DoNet folder. dll, if it is version 2.0, use Newtonsoft.Json.dll under the DotNet20 file, and then import its namespace using Newtonsoft.Json on the page you are using;
After the preparations are completed, start the demonstration below, first add the webService file naming to ProductService.asmx, and then uncomment [System.Web.Script.Services.ScriptService].
1. Traverse the collection of "name/value" pairs
ProductService.asmx Add the getProductInfoToJson method

Copy code The code is as follows:

[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);
}

Front Desk
Copy code The code is as follows:

$("#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 "
");
}
});
});

2. Traverse the ordered list of values ​​
Copy code The code is as follows:

ProductService.asmx Add GetProductList method
[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 "";
}
}

Front desk:
Copy code The code is as follows:

var suggestList = $('
    ').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) {
    $("
  • ").text(term).appendTo(suggestList);
    });
    suggestList.show();
    }
    });
    });

3. Traverse the ordered list of values ​​which contains a collection of "name/value" pairs
Copy code The code is as follows:

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 BrandNameInfoCollection = new List();
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 = [
'
'
].join('');
});
}
});

在1.41中,jquery添加了 jQuery.parseJSON( json ) 的方法,该方法的定义是Takes a well-formed JSON string and returns the resulting JavaScript object. 就是接受一个格式良好的JSON字符串,返回一个Javascript对象。
这大大方便了我们在前台对服务器端生成的Json字符串的处理.
好了,关于Jquery遍历Json两种数据结构的介绍就到这里
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn