Code for traversing two Json Data Structures Using Jquery

Source: Internet
Author: User

In ajax interaction, the data types returned from the server include xml, html, script, json, jsonp, and text. This document uses json as an example, describes how to use jquery to traverse two json data structures at the front end: a set of "name/value" pairs and an ordered list of values, and the ordered list of values contains the set of "name/value" pairs. on the server side, we use Json.. NET to serialize data structures such as arraylist, hashTable, and list.
Before starting, we need to download Json.net. After the download is complete, add references to the website to open the downloaded folder. for Versions later than net2.0, use Newtonsoft in the DoNet folder. json. dll. if the version is 2.0, use Newtonsoft in the DotNet20 file. json. dll, and then import its namespace using Newtonsoft on the page in use. json;
After the preparation is complete, the following example shows how to add the webService file named ProductService. asmx, and then cancel the comment on [System. Web. Script. Services. ScriptService.
1. traverse the set of "name/value" Pairs
ProductService. asmx Add the getProductInfoToJson Method
Copy codeThe 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-end
Copy codeThe 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 + "<br/> ");
}
});
});

2. traverse the ordered list of values
Copy codeThe Code is as follows:
ProductService. asmx Add the 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-end:
Copy codeThe Code is as follows:
Var suggestList = $ ('<ul class = "autocomplete" </ul>'). hide (). insertAfter ("# search-text ");
$ ("# Search-text"). keyup (function (){
Var textString = "{KeyWord: '" + $ ("# 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. The sorted list of traversal values contains the set of "name/value" pairs.
Copy codeThe Code is as follows:
ProductService. asmx Add the GetBrandNameByKeyword Method
[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;
}
}
}

Front-end
Copy codeThe Code is as follows:
$. 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> recipient: </B>', item. receiverName, '</br> <B> contact number: </B>', item. receiverPhoneNo, '</br> <B> detailed address: </B>', item. detailsAddress, '</font> ">', item. noticeWords, '</label> </br>'
]. Join ('');
});
}
});

In section 1.41, jquery adds jQuery. parseJSON (json) method, which is defined as Takes a well-formed JSON string and returns the resulting JavaScript object. it is to accept a well-formatted JSON string and return a Javascript Object.
This greatly facilitates the processing of Json strings generated on the server at the front end.
Okay. Here is an introduction to Jquery's two data structures for Traversing Json.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.