


Implementation code for traversing two Json data structures through Jquery_jquery
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
[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
$("#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
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:
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
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
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两种数据结构的介绍就到这里

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

目录1:basename()2:copy()3:dirname()4:disk_free_space()5:disk_total_space()6:file_exists()7:file_get_contents()8:file_put_contents()9:filesize()10:filetype()11:glob()12:is_dir()13:is_writable()14:mkdir()15:move_uploaded_file()16:parse_ini_file()17:
