Ajax instances and technical principles, and ajax instances

Source: Internet
Author: User
Tags ajax status code

Ajax instances and technical principles, and ajax instances

Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

Abstract: AJAX (Asynchronous Javascript And XML) is a web page development technology that creates interactive web applications. AJAX is a technology used to create fast dynamic web pages. By performing a small amount of data exchange with the server in the background, AJAX can implement asynchronous updates on webpages. This means that you can update a part of a webpage without reloading the entire webpage. To update content for traditional web pages (without AJAX), you must reload the entire web page.

I. Ajax technology and principles
1.1. AjaxAJAX = Asynchronous JavaScript and XML (Asynchronous JavaScript and XML ).

AJAX is not a new programming language, but a new method that uses existing standards.

AJAX is the art of exchanging data with the server and updating some webpages without reloading the entire page.

1.2 Ajax technology

We all know that ajax is not a new technology, but a combination of several original technologies. It is composed of the following technologies.

1. CSS and XHTML are used for representation.

2. Use the DOM model for interaction and dynamic display.

3. Use XMLHttpRequest to communicate with the server asynchronously.

4. Use javascript for binding and calling.

The main point of AJAX is the XMLHttpRequest object.

Different browsers use different methods to create XMLHttpRequest objects.

Use the IE browser ActiveXObjectWhile other browsers use XMLHttpRequestJavaScript built-in objects
1.3. How Ajax works

The core of Ajax is the JavaScript Object XmlHttpRequest. This object was first introduced in Internet Explorer 5. It is a technology that supports asynchronous requests. In short, XmlHttpRequest allows you to use JavaScript to request and process responses to the server without blocking users.

Let's see the difference from the traditional method.


Let's take a look at their respective interactions.

Common Browser Interaction


Ajax interaction in browsers


When creating a Web site, executing screen updates on the client gives you great flexibility. The following functions can be completed using Ajax:
Dynamically Update the total number of items in the shopping cart. You do not need to click Update and wait for the server to resend the entire page.
This improves site performance by reducing the amount of data downloaded from the server. For example, on the Amazon shopping cart page, when updating the number of items in the basket, the entire page is reloaded, which must download 32 K data. If Ajax is used to calculate the new total, the server returns only the new total value, so the required bandwidth is only 1% of the original total.
This eliminates the page refresh for each user input. For example, in Ajax, if you click Next on the page list, the server data will only refresh the list rather than the whole page.
Directly edit table data, rather than requiring users to navigate to a new page to edit data. For Ajax, When you click Edit, You can refresh the static table as an editable table. After you Click Done, you can send an Ajax request to update the server and refresh the table so that it contains static and read-only data.


1.4. Three common attributes of the XMLHttpRequest object

1. onreadystatechange attributes
The onreadystatechange attribute contains functions for processing server responses.
The following code defines an empty function. You can set the onreadystatechange attribute at the same time:

XmlHttp. onreadystatechange = function () {// here we need to write some code}
2. readyState attributes
The readyState attribute contains the status information of the server response. When the readyState changes, the onreadystatechange function is executed.
Possible values of the readyState attribute:
Status description
0 request not initialized (before calling open)
1. The request has been submitted (before sending () is called)
2. The request has been sent (the content header can be obtained from the response)
3. The request is being processed (some data is usually available in the response, but the server has not yet completed the response)
4. The request has been completed (you can access the server response and use it)
We need to add an If statement to this onreadystatechange function to test whether our response has been completed (meaning data can be obtained ):
XmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4) {// retrieve data from server response }}
3. responseText attributes
You can use the responseText attribute to retrieve the data returned by the server.
In our code, we will set the value of the time text box to be equal to responseText:
xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4){document.myForm.time.value=xmlHttp.responseText;}}

Other attributes are as follows:


1.5 xmlhttprequst Method

1. open () method
Open () has three parameters. The first parameter defines the method used to send the request. The second parameter specifies the URL of the server script. The third parameter specifies that the request should be processed asynchronously. For more information, see the blog post.

xmlHttp.open("GET","test.php",true);
2. send () method
The send () method sends the request to the server. If we assume that the HTML and PHP files are in the same directory, the Code is as follows:
xmlHttp.send(null);

For more information, see the blog post.

Other methods are as follows:


Ii. Ajax programming steps

For ease of understanding, I unified a process for AJAX. To implement AJAX, follow these steps:

(1) Create an XMLHttp object.

(2) set the request method.

(3) Call the callback function.

(4) send a request.

Next let's take a look at the specific steps:

2.1 create an XMLHttp object

The syntax for creating an XMLHttp object is:

var xmlHttp=new XMLHttpRequest();

If the browser is IE5 or IE6, the ActiveX object is used. The creation method is as follows:

var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
Generally, when writing AJAX, we first need to determine whether the browser supports the XMLHttpRequest object. If the browser supports the object, we need to create the object. If the browser does not support the object, we need to create the ActiveX object. The JS Code is as follows:

// Step 1: Create the XMLHttpRequest object var xmlHttp; if (window. XMLHttpRequest) {// create the XMLHttp object xmlHttp = new XMLHttpRequest ();} else if (window. activeXObject) {xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ")}

2.2 SET THE REQUEST METHOD

In WEB development, there are two types of requests. One is get and the other is post. Therefore, you need to set the specific request to use, the open () of the XMLHttpRequest object () the method is to set the request method.
Open ():
Function: Specifies the request type, URL, and whether to asynchronously process the request.
Parameter: parameter 1. Set the request type (GET or POST). For the difference between GET and POST, refer to Baidu. I will not explain it here;
Parameter 2: Location of the file on the server;
Parameter 3: whether to asynchronously process the request; true or false.

As follows:

// Step 2: set the parameters for interaction with the server, and send the data var url = "http: // localhost: 8080/JsLearning3/getAjax: // localhost: 8080/JsLearning3/getAjax "; xmlHttp. open ("POST", url, true );

The open method is as follows:


GET or POST?
GET is simpler and faster than POST, and can be used in most cases. However, use POST requests in the following cases:
Unable to use cached files (updating files or databases on the server)
Send large amounts of data to the server (there is no limit on the size of POST data)
When sending user input containing unknown characters, POST is more stable and reliable than GET.
Asynchronous-True or False?
AJAX refers to Asynchronous JavaScript and XML (Asynchronous JavaScript and XML ). If the XMLHttpRequest object is used for AJAX, The async parameter of its open () method must be set to true: for web developers, sending asynchronous requests is a huge improvement. Many tasks executed on the server are time-consuming. Before AJAX appears, this may cause the application to be suspended or stopped.
Through AJAX, JavaScript does not need to wait for the server's response, but rather:
Execute other scripts while waiting for Server Response
Process the response when the response is ready

2.3 call the callback function

If the third parameter of the open Method in the previous step is true, the current request is an asynchronous request. In this case, you need to write a callback function. The xmlHttp object has an onreadystatechange attribute, this attribute returns an anonymous method, so the callback function writes xmlHttp here. onreadystatechange = function {}, function {} contains the callback function content. The so-called callback function is the function that the request is processed in the background and then returned to the foreground. In this example, the function implemented by our callback function is to receive the data sent to the foreground after processing in the background, and then display the data to the specified div. Because the data returned from the background may be incorrect, you must first determine whether the information returned from the background is correct in the callback function. If yes, you can continue execution. The Code is as follows:

// Step 3: register the callback method xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4) {if (xmlHttp. status = 200) {var obj = document. getElementById (id); obj. innerHTML = xmlHttp. responseText;} else {alert ("error returned by AJAX server! ");}}}

In the code above, xmlHttp. readyState is in the state where XMLHttpRequest is stored. Changes from 0 to 4. 0: the request is not initialized. 1: The server connection has been established. 2: The request has been received. 3: The request is being processed. 4: The request is complete and the response is ready. Therefore, we can determine that the execution can continue only when xmlHttp. readyState is 4.

XmlHttp. status is the result returned by the server. 200 indicates that it is correct. 404 indicates that no page is found. Therefore, we can continue to execute the Code only when xmlHttp. status is 200.

var obj=document.getElementById("testid");obj.innerHTML = xmlHttp.responseText;
This code is the core content of the callback function, that is, to obtain the data returned by the background, and then assign this data to the div with the id testid. The xmlHttp object has two attributes that can be used to obtain the data returned by the backend: responseText and responseXML. responseText is used to obtain the response data in string form, and responseXML is used to obtain the response data in XML form. As to which data is returned from the backend, the returned data is only a string. Therefore, responseText is selected. ResponseXML will be introduced in future examples.

Differences between AJAX Status values and Status Codes
The AJAX status value refers to several States that have been used to run AJAX. no matter whether the access is successful or not, the response steps can be understood as AJAX running steps. For example, sending and responding are obtained when the AJAX object interacts with the server. You can use "ajax. readyState" to obtain the result. (From numbers 1 ~ Composed of 4 numbers)
AJAX status code indicates the HTTP header information code returned by the server based on the information submitted by the HTTP protocol, regardless of whether AJAX access is successful or not. status (consisting of numbers 1XX and 2XX. For details, see RFC)
This is why we use the following method to determine whether the obtained information is correct when using AJAX.

if(ajax.readyState == 4 && ajax.status == 200) {。。。。);}
AJAX running steps and Status values
In actual AJAX running, the access to XMLHttpRequest (XHR) is not completed at one time, but the results obtained after multiple States, for which there are five statuses in AJAX, yes.
0-(not initialized) The send () method has not been called
1-(load) The send () method has been called and a request is being sent.
2-(Load completed) The send () method is executed completely,
3-(interaction) parse the response content
4-(complete) The response content has been parsed and can be called on the client
For the above status, "0" is the status value automatically generated after the definition, and for the successful access status (get information) We mostly use "4" for judgment.

AJAX Status Code Description
1 **: request received, continue processing
2 **: The operation is successfully received, analyzed, and accepted.
3 **: the request must be further processed.
4 **: The request contains an error syntax or cannot be completed
5 **: the server failed to execute a fully valid request.

The details are as follows:

100 -- the customer must continue to send the request
101 -- the client requests the server to convert the HTTP protocol version according to the request
200 -- transaction successful
201 -- prompt to know the URL of the new file
202 -- accept and process, but not complete
203 -- the returned information is uncertain or incomplete
204 -- the request is received, but the returned information is null.
205 -- when the server completes the request, the user agent must reset the file that has been browsed.
206 -- the server has completed some users' GET requests
300 -- the requested resources can be obtained in multiple places
301 -- Delete request data
302 -- request data found at other addresses
303 -- we recommend that you access other URLs or access methods.
304 -- the client has executed GET, but the file has not changed
305 -- the requested resource must be obtained from the address specified by the server
306 -- code used in HTTP of the previous version, which is not used in the current version
307 -- declaring temporary deletion of requested resources
400 -- incorrect request, such as syntax error
401 -- authorization request failed
402 -- retain valid ChargeTo header response
403 -- the request is not allowed
404 -- no file, query, or URl found
405 -- the method defined in the Request-Line field is not allowed.
406 -- the requested resource is inaccessible due to the user's Accept drag.
407 -- similar to 401, the user must first be authorized on the Proxy Server
408 -- the client did not complete the request within the specified time
409 -- the request cannot be completed due to the current resource status
410 -- this resource is no longer available on the server and there is no further reference address
411 -- the server rejects the User-Defined Content-Length attribute request
412 -- one or more request header fields are incorrect in the current request
413 -- the requested resource is larger than the size allowed by the server
414 -- the requested resource URL is longer than the length allowed by the server
415 -- the requested resource does not support the format of the requested project
416 -- The request contains the Range request header field. There is no range indication value in the current request resource Range, and the request does not contain the If-Range request header field.
417 -- the server does not meet the expectation specified in the header field of the response CT request. If it is a proxy server, it may be that the next-level server cannot meet the request
500 -- Internal error occurred on the server
501 -- the server does not support the requested function
502 -- the server is temporarily unavailable, sometimes to prevent system overload
503 -- server overload or service suspension
504 -- the gateway is overloaded. The server uses another gateway or service to respond to the user. The waiting time is long.
505 -- the server does not support or reject the specified HTTP version in the Request Header

2.4 send a request

// Step 4: Set the content of the request to be sent and submitted. Then send the request var params = "userName =" + document. getElementsByName ("userName") [0]. value + "& userPass =" + document. getElementsByName ("userPass") [0]. value + "& time =" + Math. random (); // Add random time parameters to prevent reading of the xmlHttp cache. setRequestHeader ("Content-type", "application/x-www-form-urlencoded; charset = UTF-8"); // Add an HTTP header to the request, POST must be added if there is data !!!! XmlHttp. send (params );

To POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the send () method:

3. Application Instances

Ajax + SpringMVC for real-time data transmission

Free project download

The project directory is as follows:


The JAR package used is as follows:


Next, let's make it clear.

1, the first is the web. xml configuration, put in the WEB-INF folder

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name> JsLearning3 </display-name> <welcome-file-list> <welcome-file> index.html </welcome-file> <welcome-file> index.htm </welcome-file> <welcome-file> index. j Sp </welcome-file> <welcome-file> default.html </welcome-file> <welcome-file> default.htm </welcome-file> <welcome-file> default. jsp </welcome-file> </welcome-file-list> <! -- Unified Encoding to prevent Chinese garbled characters --> <filter-name> Set Character Encoding </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <filter-mapping> <filter-name> Set Character Encoding </filter-name> <url-pattern>/* </url-pattern> </ filter-mapping> <! -- Front-end controller of SpringMVC --> <servlet-name> dispatcherServlet </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <! -- Set the custom controller xml file --> <init-param> <param-name> contextConfigLocation </param-name> <param-value> classpath *: spring-servlet.xml </param-value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <! -- Spring MVC configuration file ended --> <! -- Intercept settings --> <servlet-mapping> <servlet-name> dispatcherServlet </servlet-name> <! -- All requests are intercepted by SpringMVC --> <url-pattern>/</url-pattern> </servlet-mapping> <! -- WebAppRootKey: The default value is webapp. root: when multiple applications are deployed under tomcat (log4j is used for each application. this parameter must be configured in xml. $ {webapp. root} Otherwise, the webAppRootKey value of each application is the same, A conflict occurs --> <context-param> <param-name> webAppRootKey </param-name> <param-value> webApp. root </param-value> </context-param> <! -- Log4jConfigLocation: log4j configuration file storage path --> <context-param> <param-name> log4jConfigLocation </param-name> <param-value> classpath: log4j. properties </param-value> </context-param> <! -- 3000 indicates opening a watchdog thread to scan configuration file changes every 60 seconds; this makes it easy to change the log storage location --> <context-param> <param-name> log4jRefreshInterval </param-name> <param-value> 3000 </param-value> </ context-param> <listener-class> org. springframework. web. util. log4jConfigListener </listener-class> </listener> </web-app>

2, then configure SpringMVC interception rule spring-servlet.xml, put in the src folder

<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p" xsi: schemaLocation = "http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http: // w Ww.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <! -- Convert the class marked with @ Controller annotation to bean --> <context: component-scan base-package = "com. lin. controller"/> <! -- Start the annotation function of Spring MVC to map requests and POJO annotations --> <bean class = "org. springframework. web. servlet. mvc. annotation. AnnotationMethodHandlerAdapter"/> <! -- Resolve the Model View name, that is, add the prefix suffix --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "p: prefix ="/WEB-INF/views/"p: suffix = ". jsp "/> </beans>
3. Use the log printing function log4j. Create log4j. properties in the src folder. skip this step if you do not need it.

The content is as follows:

log4j.rootLogger =DEBEG,stdoutlog4j.appender.stdout = org.apache.log4j.ConsoleAppender  log4j.appender.stdout.Target = System.out  log4j.appender.stdout.layout = org.apache.log4j.PatternLayout  log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n  

4. Use of Ajax

Create a view folder under the WEB-INF and create a first. jsp file with the following content:

<% @ 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"> 

5. Controler Controller

package com.lin.controller;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class firstController {private static Logger logger = Logger.getLogger(firstController.class);    @RequestMapping({"/first","/"})public String getFirst(){  return "first";}@RequestMapping({"/getAjax/**"})public String getAjax(HttpServletRequest request, HttpServletResponse response) throws IOException{String userName=(String)request.getParameter("userName");String userPass=(String)request.getParameter("userPass");System.out.println(userName);System.out.println(userPass);List<String> list=new ArrayList<String>();list.add(userName);list.add(userPass);JSONArray json = JSONArray.fromObject(list);  response.setCharacterEncoding("UTF-8");response.flushBuffer();response.getWriter().write(json.toString());return null;}}
Here we use to convert submitted data to Json for saving, process various requests, and set Ajax return parameters.

If a focus event is lost in the name or password input column, a request is immediately sent to the server.

After all settings are complete, you can run it.

The result is not displayed. The input is a Json array, the first is the user name, and the second is the password.

As we can see, as long as the input box loses the focus event, it will immediately submit the data, and then the server will return the result. Here I have directly returned the original value. Think about it. In fact, during many registration, the user name is verified repeatedly, but the query to the database is added in the Controller layer, to determine whether the name entered by the user exists. Then return the result. In the next lecture, we will describe it in the future.


Copyright Disclaimer: This article is the original article by the blogger Lin bingwen Evankaka, which cannot be reproduced without the permission of the blogger.

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.