jquery parsing JSON format data

Source: Internet
Author: User

A little bit of learning about JSON today,JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

JSON is constructed in two structures:

    • A collection of name/value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object) , record (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative array).
    • The sequence of values (an ordered list of values). In most languages, it is understood as an array (array).

These are common data structures. In fact, most of the modern computer languages support them in some form. This makes it possible for a data format to be exchanged between programming languages that are also based on these constructs.

The JSON has these forms:

An object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).

Okay, let's just go straight to the example!! This small demo design is like this, index.jsp page access server-side servlet,servlet to index.jsp pass data, pass the data when the JSON format, hehe ... Nonsense, if it's not JSON-formatted data, I'm writing this blog as a fool of the audience!

Index.jsp the Code of the end (first easy after the difficult order):

<%@ page language= "Java"Import= "Java.util.*"pageencoding= "UTF-8"%> <% String Path=Request.getcontextpath (); String BasePath=Request.getscheme ()+"://" +Request.getservername ()+":"+Request.getserverport () +Path+"/"; %> <! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en" > href= "<%=basePath%>" > <title>my JSP' Index.jsp 'Starting page</title> <meta http-equiv= "Pragma"Content= "No-cache" > <meta http-equiv= "Cache-control"Content= "No-cache" > <meta http-equiv= "Expires"content= "0" > <meta http-equiv= "keywords"Content= "Keyword1,keyword2,keyword3" > <meta http-equiv= "description"Content= "This is my page" > <!--<link rel= "stylesheet"Type= "Text/css"href= "Styles.css"mce_href= "Styles.css" > <mce:script type= "Text/javascript"src= "Js/jquery-1.3.2.js" mce_src= "js/jquery-1.3.2.js" ></mce:script> <mce:script type= "text/ JavaScript " src=" js/login.js " mce_src=" js/login.js "></mce:script>

Then there are two bean programs: person and address. The design of these two classes here is primarily a better embodiment of the way JSON passes data and the data format passed

Package com.wk; PublicClassperson {PrivateString FirstName; PrivateString LastName; PrivateAddress address; PublicPerson () {super ();Person (string firstName, String lastName, address address) {super (); this.firstname=FirstName; This.lastname=LastName; This.address=Address } publicString Getfirstname () {returnFirstName; } publicvoidSetfirstname (String firstName) {This.firstname=FirstName; } publicString Getlastname () {returnLastName; } publicvoidSetlastname (String lastName) {This.lastname=LastName; } publicAddress getaddress () {returnAddress } publicvoidSetaddress (address) {this.address=Address }} package Com.wk; PublicClassAddress {PrivateIntId PrivateString detail; PublicAddress () {super ();} publicAddress (intID, String detail) {super (); this.id=Id This.detail = detail;} public int getid () {Return id; } public void setId (Int id) {this.id = id; } public string Getdetail () {return  detail; } public void setDetail ( String detail) {this.detail =  Detail } }

Servlet Code:

Package com.servlet; Import java.io.IOException; Import Java.io.PrintWriter; Import java.util.ArrayList; Import java.util.List; Import javax.servlet.ServletException; Import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; Import com.wk.Address; Import Com.wk.Person; PublicClassPersonservlet extends httpservlet{privateStaticFinalLongSerialversionuid=1L; StaticStringBuffer BF; @Override protectedvoidDoget (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {resp.setcontenttype (" Text/html;charset=utf-8 "); List<person>Persons=NewArraylist<person> (); PrintWriterOut=Resp.getwriter ();
Person Person1=NewPerson (); Address A1=NewAddress (); A1.setid (1); A1.setdetail ("Hebei province"); Person1.setfirstname ("melon"); Person1.setlastname ("silly"); Person1.setaddress (A1); Persons.add (Person1);
Person Person2=NewPerson (); Address A2=NewAddress (); A2.setid (2); A2.setdetail ("Jiangxi Province"); Person2.setfirstname ("egg"); Person2.setlastname ("dumb"); Person2.setaddress (A2); Persons.add (Person2);
Person Person3=NewPerson (); Address A3=NewAddress (); A3.setid (1); A3.setdetail ("Hunan province"); Person3.setfirstname ("fetish"); Person3.setlastname ("white"); Person3.setaddress (A3); Persons.add (Person3);
Bf=NewStringBuffer ();
/*Assemble the string in JSON format * {"Person": [* {"FirstName": "", "Lastnmae": "", "address": {"id": "", "Detail": "}}, *]} */Bf.append (" {\ "PE rson\ ": ["); for (person person:persons) {bf.append ("{\" firstname\ ": \" "). Append (Person.getfirstname ()). Append (" \ ", \" "). Append ( "lastname\": \ ""). Append (Person.getlastname ()). Append ("\", "). Append ("\" address\ ":"). Append ("{\" id\ ": \" "). Append (Person.getaddress (). GetId ()). Append (" \ ", \" "). Append (" detail \ ": \" "). Append (Person.getaddress (). Getdetail ()). Append (" \ ""). Append ("}},"); }//Subtract the last comma from intLength = bf.length (); String newstr = bf.substring (0, length-1); bf = new stringbuffer (); Bf.append (NEWSTR) ;
Bf.append ("]}"); OUT.PRINTLN (BF); } @Override protected void doPost (httpservletrequest req, HttpServletResponse resp) throws Servletexception, IOException {this.doget (req, resp);}
}

The following code is how jquery parses JSON data and is the core code of this demo:

$ (document). Ready (function () {$ ("table"). CSS ("Border-color","LightBlue"). CSS ("Border-style","Solid"); $ ("#head"). CSS ("Background-color","LightBlue"); $.ajax ({//Background handler URL:"Json",//Data transmission type:"POST",//Accept data Format DataType:  "JSON", timeout:  20000,//< Span class= "Apple-converted-space" >  set request time-out (milliseconds).   the callback function after the request succeeds. Success:function (dataobj) {var member =  eval (dataobj);// alert ( Member.person[1].firstname); $ (Dataobj.person). Each (function (I, per) {$ ("#tr"  + i). Find (" #td0 "). HTML (per.lastname); $ ("#tr"  + i). Find ("#td1"). HTML (per.firstname); $ ("#tr"  + i). Find ("#td2"). HTML (per.address.detail); }); } }); });

Put a run effect on it again!!

Oh.... Common learning and common progress!!!!!!!

jquery parsing JSON format data

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.