Ajax JSON framework

Source: Internet
Author: User
In fact, the core idea of JSON is the conversion of objects and strings on the server and client. jar and JSON. by using JS, the server can automatically convert the received data to the entity, and the client no longer has to worry about concatenating strings.
It is a better data format than XML:
1) represents a complex data structure.
2) It can be easily parsed on both the client and server.
-----------------------------------------------------------------------
JSON:
1. defines a format for describing data.
Student (ID, name, age, email );

"{'Id': '1', 'name': 'hangsan', 'age': 10,
'Email ': 'zhangsan @ cernet.com ',
'Address': {'street ': 'xxxx', 'postcode': '123'
},
'Phone': ['000000', '000000', '000000']
}"

2. JSON. js provides two functions.
JavaScript Object <---> Str
|-> Stringify (object) --> Str
|-> Parse (STR) --> OBJ
3. JSON. jar in the server-side Java Code To convert the JSON string.

XMLHttpRequest
|-> User {ID, name, age, email.} [JavaScript]
|-> JSON. JS --> string (JSON format ).


String (JSON format) ==> server (Java object)
==> JSON. Jar (string --> JAVA object)

{"ID": 1,
"Name": "zhangsan ",
"Age": 20,
"Email": ["emaila", "emailb", "emailc"],
"Address": {"street": "AAAAA", "postcode": "1234 "}
}

JSON. stringify (OBJ) ==> STR:
Called before sending data to the server, the data to be sent is stored in the object OBJ --- stringify --> STR ==> Server

JSON. parse (STR) --> OBJ:
After receiving the Server Response (STR), call parse to convert the server response string to an object and use the data in it.
Client:
Button --> onclick --> Reg ()
|-> Createuser
|-> JSON. stringify ()-> string
|-> Send (string )....

Serlvet:
Readjsonstring (): Get string from request.
New jsonobject (STR );
Insert (): Get data from jsonobject
Respnose:
|-> OK
|-> Error;


Reqcallback ()
|-> Alert (OK );
|-> Alert (error );
How the server receives data from the client:
Request. getinputstream ()
==> Inputstream [==> bufferedreader]
==> Is. Read () | Br. Readline () => xmldata

Bytes --------------------------------------------------------------------------------------------------------------
The following is the sample code:
========================================================== ========================================================== ====================================
// This is the conversion between object strings on the page
<HTML>
<Head>
<SCRIPT type = "text/JavaScript" src = "./JSON. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
Function teststringify (){
VaR OBJ = new object ();
OBJ. ID = 1;
OBJ. Name = "zhangsan ";
OBJ. Age = 20;
OBJ. Email = ["emaila", "emailb", "emailc"];
OBJ. Address = {Street: "AAAAA", postcode: "1234 "};

VaR STR = JSON. stringify (OBJ );
Document. Write ("}

Function testparse (){
VaR STR = '{"orderitem": [{"Number": 10, "product": {"ID": 1, "name": "book", "price ": 10 }},{ "Number": 2, "product": {"ID": 2, "name": "USB", "price": 100 }}, {"Number": 3, "product": {"ID": 3, "name": "DVD", "price": 5}]} ';
VaR order = JSON. parse (STR );
For (VAR I = 0; I <order. orderitem. length; I ++ ){
Document. Write ("Document. write ("Document. Write ("<HR/> ");
}
}
</SCRIPT>
</Head>
<Body>
<Input type = "button" value = "test stringify" onclick = "teststringify ();"/>
<Input type = "button" value = "test parse" onclick = "testparse ()"/>
</Body>
</Html>

========================================================== ========================================================== ====================================
// This is to test the conversion from a string to an object and convert an object to a string in Java.
Package test. Ajax. JSON;
Import org. JSON .*;

Public class testjsonobject {
Public static void main (string ARGs []) throws exception {
// Received string
String STR = "{\" ID \ ": 1, \" Name \ ": \" testjson \ ", \" Age \ ": 20, \" email \": [\ "emaila \", \ "emailb \", \ "emailc \"], \ "address \" :{\ "street \": \ "AAAAA \", \ "postcode \": \ "1234 \"}}";
// The above/"is a conversion character. In fact, the root cause of this string is the distinction:" {'id': 1, 'name': 'testjson ', 'age': 20, 'email ': ['emaila', 'emailb', 'emailc'], 'address': {'street': 'aaaaa ', 'postcode': '000000 '}}"
// Convert a string to an object
Jsonobject JSON = new jsonobject (STR );
// Output after conversion
System. Out. println ("ID =" + JSON. getint ("ID "));
System. Out. println ("name =" + JSON. getstring ("name "));
System. Out. println ("age =" + JSON. getint ("Age "));
// Array receiving
Jsonarray array = JSON. getjsonarray ("email ");
For (INT I = 0; I <array. Length (); I ++ ){
System. Out. println (array. getstring (I ));
}
// Object processing method in the object
Jsonobject address = JSON. getjsonobject ("Address ");
System. Out. println ("street" + address. getstring ("street "));
System. Out. println ("postcode" + address. getstring ("postcode "));
// Convert an object to a string
System. Out. println (JSON. tostring ());
}
}
========================================================== ========================================================== ======================================
The following is an example of an application in the front and back end:
Regservlet. Java
**************************************** **************************************** *********************************
Package com. kettas. Ajax;

Import java. Io .*;

Import javax. servlet. servletexception;
Import javax. servlet. http .*;

Public class regservlet extends httpservlet {
@ Override
Public void Service (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {
Response. setcontenttype ("text/html ");
Printwriter out = response. getwriter ();
Try {
String jsonstr = readjsonstring (request );
System. Out. println (jsonstr );
// Return a successful response
Out. Print ("OK ");
Out. Flush ();
} Catch (exception e ){
E. printstacktrace ();
// Response to failure
Out. Print ("error ");
Out. Flush ();
}

}

Private string readjsonstring (httpservletrequest request) throws exception {
Inputstream is = request. getinputstream ();
Bufferedreader BR = new bufferedreader (New inputstreamreader (is ));
String STR = "";
String temp = "";
While (true ){
Temp = Br. Readline ();
If (temp = NULL ){
Break;
}
STR + = temp;
}
Return STR;
}
}
========================================================== ========================================================== ======================================
Register.html
**************************************** **************************************** *********************************
<HTML>
<Head>
<SCRIPT type = "text/JavaScript" src = "./JSON. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript">
VaR xhr;
// Initialize the xhr object
// Return value: 1: IE, 2, ILA Ila, 0: Create xhr error;
Function createxhr (){
// 1. Create an xhr object.
If (window. activexobject ){
Xhr = new activexobject ("Microsoft. XMLHTTP ");
Return 1;
} Else if (window. XMLHttpRequest ){
Xhr = new XMLHttpRequest ();
Return 2;
} Else {
Return 0;
}
}
/// // Execute user registration /////////////////// ///
Function Reg (){
// 1. Create and initialize the user object
VaR user = createuser ();
// 2. Convert the user object to the string to be sent (in JSON format)
VaR STR = JSON. stringify (User );
// 3. Create an xhr object
Createxhr ();
// 4. Send the request
Xhr. onreadystatechange = regcallback;
Sendregrequest (STR );
}
Function createuser (){
VaR user = new object ();
User. Name = Document. getelementbyid ("nameid"). value;
User. Password = Document. getelementbyid ("passwordid"). value;
User. Email = Document. getelementbyid ("emailid"). value;
User. Phone = Document. getelementbyid ("phoneid"). value;
Return user;
}
Function sendregrequest (data ){
Xhr. Open ("Post", "/ajax/Reg ");
Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
Xhr. Send (data );
}
Function regcallback (){
If (xhr. readystate = 4 ){
If (xhr. Status = 200 ){
Handleregresult ();
} Else {
Alert ("error, status =" + xhr. status );
}
}
}
Function handleregresult (){
// Alert (xhr. responsetext );
If (xhr. responsetext = "OK "){
Alert ("Reg OK ");
} Else if (xhr. responsetext = "error "){
Alert ("system is busy, please try again later .");
} Else {
Alert ("error! ");
}
}
</SCRIPT>
</Head>
<Body>
<H1> User register <Table>
<Tbody>
<Tr>
<TD> User Name </TD>
<TD> <input type = "text" id = "nameid"/>
<Span id = "msgid"> </span>
</TD>
</Tr>
<Tr>
<TD> password </TD>
<TD> <input type = "password" id = "passwordid"/> </TD>
</Tr>
<Tr>
<TD> email </TD>
<TD>
<Input type = "text" id = "emailid"/>
</TD>
</Tr>
<Tr>
<TD> Phone: </TD>
<TD> <input type = "text" id = "phoneid"/> </TD>
</Tr>
<Tr>
<TD colspan = "2">
<Input type = "button" value = "user register" onclick = "Reg ()"/>
</TD>
</Tr>
</Tbody>
</Table>
</Body>
</Html>
========================================================== ========================================================== ======================================
Web. xml
**************************************** **************************************** *********************************
<? XML version = "1.0" encoding = "ISO-8859-1"?>
<Web-app xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
Version = "2.5">
<Servlet>
<Servlet-Name> regservlet </servlet-Name>
<Servlet-class> com. kettas. Ajax. regservlet </servlet-class>
</Servlet>

<Servlet-mapping>
<Servlet-Name> regservlet </servlet-Name>
<URL-pattern>/REG </url-pattern>
</Servlet-mapping>
</Web-app>

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.