11.Ajax JSON

Source: Internet
Author: User

Overview:

The development steps of **AJAX technology and its introduction (the steps of development are fixed) **1. Learn Ajax to master XMLHttpRequest objects. * Using asynchronous techniques, you need to use the XMLHttpRequest object. * The object encapsulates the HTTP protocol * can also use GET or post to request the server * to get server-side response content * response is a string or XML document 2.AJAX technology development, the steps to write code is fixed. 3. Development of the introductory Step (fixed) var xhr = new XMLHttpRequest ();--support for Firefox, Google, or IE's high-version browser * First step: Need to get to XMLHttpRequest object first.  function createxmlhttprequest () {try {///If you are the IE high version of Firefox Google return new XMLHttpRequest ();} catch (e) {try {///If it is a version of IE6 return New ActiveXObject ("Msxml2.xmlhttp");} catch (e) {try {//If it is IE5.5 version return new ActiveXObject ("Microsoft.XMLHTTP");} catch (E) {alert ("Big Brother! What browser are you here!! ");}}}} * Step Two * If the first step has already acquired the XMLHttpRequest object, next, the connection is required to access the server-side resources. * Open ("Request Method", "Path to request Resource", Boolean); * 3 Methods meaning * 1. The way to represent the request, commonly used to have get or post* 2. Represents the path of the requested resource, for example: ${ Pagecontext.request.contextpath}/xxxservlet* 3. A value that is a Boolean value, if True, indicates that the asynchronous operation, if False, is a synchronous operation. In general, true* is the third step * Send request Parameters * Send (request body content); * If the request is a POST request, the parameters are passed normally in the Send method. Xhr.send ("username=" +haha+ "&password=" +123) * If the request method is a GET request, the Send method generally does not pass parameters. * You can use the open method to pass parameters: for example: ${pagecontext.request.contextpath}/xxxservlet?username=haha* If a GET request is not typically passed with a parameter, send generally passes nullxhr.send (null); * Fourth Step * Overall Purpose: Receive server-side response. But how to receive it? * XMLHttpRequest provides properties that use this property to listen for changes in the state of the XMLHttpRequest object. The XMLHttpRequest object by which state * 0--just created the object * The call to the Open method, no request has occurred * 2--has called the Send method, sent the request, but has not received a response * 3--responded, but it is possible that the response did not end * 4-- The response is complete * Code as follows Xhr.onreadystatechange = function () {//To make a judgment, if the Xhr object state is already 4, indicating that the response has ended//not only will determine whether the state is 4, but also determine whether the status code is 200if ( Xhr.readystate = = 4 && xhr.status = = 200) {//At that location, gets the contents of the response. Code to receive the response var result = Xhr.responsetext;}}; * Fifth Step * receive the contents of the response * If the server side responds to a string, var result = Xhr.responsetext;result is the string * If the server side responds to the contents of the XML, var result = Xhr.responsexml Result represents the Document object (not now)

* * Examples of getting Started * *

1. Requirements: On the JSP page, provide a button, click the button, secretly send an asynchronous request (page not submitted), let the button below the 2. Writing code
* Client
* Adopt the asynchronous Way
* Using XMLHttpRequest Object

* Server-side
* Output A word in the console
* The contents of the response string

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Ajax1servlet:

public class Ajax1servlet extends HttpServlet {protected void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {System.out.println ("request succeeded");//Respond Response.getwriter (). Print (" Hello ajax!! ");} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {} }

  

**ajax sending a POST request * *

1. Post requests sent to the server
* Xhr.open ("POST", "address", true)
* Set the requested header information
* Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
* Xhr.send (parameter);

2. Writing code to demonstrate a POST request

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Ajax2servlet:

public class Ajax2servlet extends HttpServlet {protected void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {System.out.println ("request succeeded"); String Username=request.getparameter ("username"); System.out.println ("Name:" +username); Response.getwriter (). print (username);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}

  

**ajax completion of user name already exists * *

1. Requirements: Verify that the user name already exists?
2. Preparing the Environment
* Client
* Registered JSP page

* Server-side
* Background of the program, through the user name sent to the database query
* If the user name already exists in the database, the description cannot be registered!
* If the user name does not exist, you can register!

REGIST.JSP:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Userservlet:

Package Demo1;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class UserServlet Extends HttpServlet {protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/** * Receive request parameters * Go to database query * If you can query, the user is already present in the database, cannot register * If the query does not exist in the database, the user can register *///may be garbled requ Est.setcharacterencoding ("Utf-8");//Response to Chinese Response.setcontenttype ("Text/html;charset=utf-8"); String Username=request.getparameter ("username"); SYSTEM.OUT.PRINTLN (username);//write Dead//If you enter admin, Prompt user name already exists if ("admin". Equals (username)) {response.getwriter (). Print ("<font color= ' Red ' > Pro, the user already exists </font>"); Else{response.getwriter (). Print ("<font color= ' green ' > Pro, can register </font> ');}} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception {doget (request, Response);}} 

  

Overview of the **json data format * *

1.json Overview: JS provides a format for data exchange data. In general, the background is stitched into JSON data, responding to the foreground. The use of JS code makes it very easy to manipulate JSON.
Specification for 2.json data formats
* The definition JSON data format must be enclosed in {}, which is provided externally as an object.
* For example: var person = {}; format of the JSON data how the person provides the object

* The object contains attributes and values, and if it is an attribute, it must be enclosed in double quotes, requiring: single quotes cannot be used.
* var person = {' name ': ' Zhang San ', ' Age ': ' Love ': [' basketball ', ' Football ']};

* What types of values can appear?
* NULL
* Digital
* String
* array using [] enclosed
* Boolean True or False

3. Specification for defining JSON formats
* var person = {' name ': ' Zhangsan ', ' Age ': 18};
* include attribute and attribute values using a colon (:)
* attribute and attribute are comma (,)
* Gets the value of the property person.name or Person.age

4. Complete the interaction between the front and rear stations
* Send data in JSON data format from background. Use JS to parse the data at the foreground.

5. The JSON-formatted data from the background response to the foreground is performed once using the Eval function.
* Using the Eval function global function, you can execute JS code and execute the concatenation of parentheses
* For example: var msg = eval ("(" +text+ ")");
* You must use the Eval function, and the result is the JSON object.

The most basic JSON:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

JSON for front and back interaction:

Json1servlet:

/** * Server-side generated JSON-formatted data, responsive to client * @author MJL * */public class Json1servlet extends HttpServlet {protected void doget (HttpS Ervletrequest request, HttpServletResponse response) throws Servletexception, IOException {System.out.println ("request succeeded") ;//Manually stitching the JSON-formatted string in response back to string p= "{\" name\ ": \" tom\ ", \" age\ ":"; "; Response.getwriter (). print (P);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {} }

JSON2.JSP:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

  

Use of the **jsonlib tool class * *

1. Function: The tool class provided in the background can convert JavaBean into a string in JSON data format.
2.json-lib Open-source jar package.
* Import the appropriate jar package.

3. Remember that these two classes
* Jsonobject
* Remember this class as a map collection.
* Some of the methods available
* Put (Key,value)
* Static method: Fromobject (JavaBean) passed in, return the Jsonobject class
* All have a ToString () method that converts the JSON data format of the Jsonobject string

* Jsonarray
* Remember this class as a list collection.
* Add (JavaBean)--Returns an array-like JSON format.
* ToString ()--forwards the Jsonarray string JSON data format

4. Summary
* Jsonlib Tool class to convert objects to JSON-formatted strings on the server side.
* Available in two classes
* Jsonobject
* Put (Key,value)
* Static method, Fromobject (Object)
* ToString (), converts a JSON-formatted string

* Jsonarray
* Add ()
* ToString (), converts a JSON-formatted string

/** * Demo Jsonlib tool class use * @author MJL * */public class Jsondemo {/** * Demo method * Jsonobject Put method */@Testpublic void run1 () {//Gen Build Jsonobject Object Jsonobject j=new jsonobject ();//Call Put method J.put ("name", "Zhang San"), J.put ("age", 18);//Generate JSON-formatted string msg= J.tostring ();//Response MsgSystem.out.println (msg);} /** * Convert the Product object to a JSON-formatted string * var pp={"P": {"pname": "Story", "Price": Ten}} * alert (pp.p.pname); */@Testpublic void run2 () {jsonobject j=new jsonobject (); Product P=new Product ("storytelling", 10);//Generate JSON-formatted data j.put ("P", p);//Generate JSON-formatted string msg=j.tostring ();// Response MsgSystem.out.println (msg);} /** * Convert object to JSON-formatted string * var p={"pname": "Story", "Price": ten} * p.pname */@Testpublic void Run3 () {Product p=new product ("storytelling", 1 0); Jsonobject J=jsonobject.fromobject (P);//Generate JSON-formatted string msg=j.tostring ();//Response MsgSystem.out.println (msg);} /** * var p=[{"pname": "Story", "Price": 10},{"PName": "Programming Idea", "price": All-in}] * P[0].pname */@Testpublic void Run4 () {Product p= New Product ("storytelling", 10); Product P1=new Product ("Programming Idea", 90); Jsonarray j=new Jsonarray ();//Call ADD method J.add (p); J.add (p1); String msg=j.tostring (); SYSTEM.OUT.PRINTLN (msg);}}

  

  

  

  

  

  

11.Ajax JSON

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.