Home  >  Article  >  php教程  >  Introduction to Ajax Programming

Introduction to Ajax Programming

黄舟
黄舟Original
2016-12-15 09:44:301142browse

1. The main reasons for using Ajax

1. Achieve a better user experience through appropriate Ajax applications;

2. Transfer some of the previous work burdened by the server to the client, which facilitates the client’s idle processing power. , reduce the burden on servers and bandwidth, thereby achieving the purpose of saving ISP space and bandwidth rental costs.

2. Quote

Jesse James Garrett, the earliest proposer of the concept of Ajax, believes that: Ajax is the abbreviation of Asynchronous javaScript and xml. Ajax is not a new language or technology. It is actually several technologies combined in a certain way to play their respective roles in a common collaboration. It includes:

·Using XHTML and CSS to standardize presentation;

·Use DOM to achieve dynamic display and interaction;

·Use XML and XSLT for data exchange and processing;

·Use xmlhttpRequest for asynchronous data reading;

·Finally use Javascript to bind and process all data;

Ajax The working principle is equivalent to adding an intermediate layer between the user and the server, making the user operation and server response asynchronous. Not all user requests are submitted to the server. Some data verification and data processing are left to the Ajax engine itself. Only when it is determined that new data needs to be read from the server, the Ajax engine will submit the request to the server on its behalf.

3. Overview

Although Garrent lists 7 Ajax constituent technologies, I personally believe that the core of so-called Ajax is only JavaScript, XMLHTTPRequest and DOM. If the data format used is XML, XML can also be added This item (the data returned by Ajax from the server can be in XML format or other formats such as text).

In the old interaction method, the user triggers an HTTP request to the server, and the server processes it and then returns a new HTHL page to the client. Whenever the server processes a request submitted by the client, the client can only Waiting idle, and even if it is just a small interaction and only needs to get a simple piece of data from the server, a complete HTML page will be returned, and the user will waste time and bandwidth to re-read the entire page every time.

After using Ajax, users feel that almost all operations will respond quickly without waiting for page reload (white screen).

1. XMLHTTPRequest

One of the biggest features of Ajax is that it can transmit or read and write data to the server without refreshing the page (also known as updating the page without refreshing). This feature mainly benefits from the XMLHTTP component XMLHTTPRequest object. In this way, the desktop application can only exchange data with the server without having to refresh the interface every time or submit the data processing work to the server every time. This not only reduces the burden on the server but also speeds up the processing time. Response speed and shortened user waiting time.

The earliest application of XMLHTTP was Microsoft. IE (IE5 and above) extended its functions by allowing developers to use XMLHTTP ActiveX components inside Web pages. Developers can directly transfer data to the server or from the server without navigating from the current Web page. The server fetches data. This feature is important because it helps reduce the pain of stateless connections, and it can also increase the speed of the process by eliminating the need to download redundant HTML. Mozilla (Mozilla 1.0 and above and NetScape 7 and above) responded by creating its own inherited XML proxy class: the XMLHttpRequest class. Konqueror (and Safari v1.2, also a KHTML-based browser) also supports the XMLHttpRequest object, and Opera will also support the XMLHttpRequest object in its v7.6x+ and later versions. For the most part, the XMLHttpRequest object is very similar to the XMLHTTP component, and the methods and properties are similar, except that a small number of properties are not supported.

Application of XMLHttpRequest:

·Application of XMLHttpRequest object in JS

var xmlhttp = new XMLHttpRequest();

·Application of Microsoft's XMLHTTP component in JS

var xmlhttp = new ActiveXObject(Microsoft.XMLHTTP) ;

var xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);

XMLHttpRequest object method

/**

* Cross-browser XMLHttpRequest instantiation.

*/

if (typeof XMLHttpRequest == 'undefined') {

 XMLHttpRequest = function () {

var msxmls = ['MSXML3', 'MSXML2', 'Microsoft']

for (var i=0; i < msxmls.length; i++) {

try {

return new ActiveXObject(msxmls[i ] + '.

// Attempt to create it "the Mozilla way"

if (window. ActiveXObject) {

 return new ActiveXObject(getXMLPrefix() + ".

Method Description
abort() Stop the current request
getAllResponseHeaders() Return the complete headers as a string
getResponseHeader("headerLabel") Return a single header label as a string
open("method","URL"[, asyncFlag[,"userName"[, "passWord"]]]) Set the target URL, method, and other parameters of the pending request
send(content) Send the request
setRequestHeader("label", "value") Set the header and Sent together with the request


XMLHttpRequest Object properties

Property Description
onreadystatechange Event trigger for state change
readyState Object state (integer):

0 = Not initialized

1 = Reading

2 = Read

3 = Interacting

4 = Completed
responseText The text version of the data returned by the server process
responseXML The DOM-compatible XML document object of the data returned by the server process
status The status code returned by the server, such as: 404 = "File not found" , 200 = "success"
statusText Status text information returned by the server


2. JavaScript

JavaScript is a programming language widely used in browsers. It has been belittled as a bad language in the past (he is indeed It is relatively boring in use) and is often used for show-off gadgets and pranks or for monotonous and trivial form validation. But the fact is that it is a real programming language, has its own standards and is widely supported in various browsers.

3. DOM

Document Object Model.

DOM is a set of APIs for HTML and XML files. It provides a structural representation of the file, allowing you to change its content and visibility. Its essence is to establish a bridge between web pages and Script or programming languages.

All properties, methods and events that WEB developers can operate and create files are represented by objects (for example, document represents the object "the file itself", table object represents the HTML table object, etc.). These objects can be accessed from Script by most browsers today.

A webpage built with HTML or XHTML can also be regarded as a set of structured data. These data are sealed in DOM (Document Object Model). DOM provides support for reading and writing various objects in the webpage.

4. XML

Extensible Markup Language (Extensible Markup Language) has an open, extensible, self-describing language structure, and it has become a standard for online data and document transmission. It is a language used to describe data structures, just like its name. It makes it easier to define certain structured data and to exchange data with other applications.
5. Comprehensive 5. Advantages of Ajax

The Ajax engine mentioned by Jesse James Garrett is actually a relatively complex JavaScript application used to process user requests, read and write servers, and change DOM content.

JavaScript's Ajax engine reads information and interactively rewrites the DOM, which enables seamless reconstruction of web pages, that is, changing page content after the page has been downloaded. This is something we have been doing extensively through JavaScript and DOM The method used, but to make the web page truly dynamic, not only internal interaction is required, but also data needs to be obtained from the outside. In the past, we let users enter data and change the content of the web page through the DOM, but now, XMLHTTPRequest can Let's read and write data on the server without reloading the page, minimizing user input.

XML-based network communication is not a new thing. In fact, both Flash and JAVA Applet have good performance. Now this kind of rich interaction is also available on the web. It is based on standardized and widely supported technologies and does not require Plug-in or download applet.

Ajax is a transformation of traditional WEB applications. In the past, the server generated an HTML page each time and returned it to the client (browser). In most websites, at least 90% of many pages are the same, such as: structure, format, header, footer, advertisements, etc. The only difference is a small part of the content, but every time the server will generate all Returning the page to the client is an invisible waste, whether it is the user's time, bandwidth, CPU consumption, or the bandwidth and space rented by the ISP at a high price. If calculated on a page basis, only a few K or dozens of K may not be impressive, but for a large ISP like SINA that generates millions of pages every day, it can be said to be a huge loss. AJAX can serve as the middle layer between the client and the server to handle the client's request and send the request to the server as needed. You can get what you use and how much you use, so there will be no redundancy and waste of data. , reducing the total amount of data downloaded, and there is no need to reload the entire content when updating the page. Only the part that needs to be updated can be updated. Compared with the pure background processing and reloading method, the user waiting time is shortened and the waste of resources is reduced. Minimized, based on standardized and widely supported technologies, and requiring no plug-ins or downloaded applets, Ajax is a win-win for both users and ISPs.

Ajax separates the interface and application in the WEB (it can also be said to separate data and presentation). In the past, there was no clear boundary between the two. The separation of data and presentation is conducive to division of labor and cooperation and reduces the number of non-technical personnel. Modifications to pages cause WEB application errors, improve efficiency, and are more suitable for current publishing systems. You can also transfer some of the previous work burdened by the server to the client, which is beneficial to the client's idle processing power.

4. Application

The emergence of the Ajax concept has opened the prelude to the era of updating pages without refreshing, and has the tendency to replace the use of form (form) submission in traditional web development to update web pages, which can be regarded as a milestone. But Ajax is not applicable everywhere, and its scope of application is determined by its characteristics.

An example of an application is an Ajax application for cascading menus.

Our previous handling of cascading menus was as follows:

In order to avoid reloading the page caused by each operation on the menu, we did not use the method of calling the background every time, but all the cascading menus were processed at once. All the data is read out and written into the array, and then JavaScript is used to control the presentation of its subset of items based on the user's operations. This solves the problems of operation response speed, not reloading the page, and avoiding frequent requests to the server, but If the user does not operate the menu or only operates part of the menu, part of the read data will become redundant data and waste the user's resources, especially when the menu structure is complex and the amount of data is large. (For example, the menu has many levels, and each level has hundreds of items), this disadvantage is even more prominent.

If Ajax is applied in this case, the results will be improved:

When initializing the page, we only read out all the data of its first level and display it. When the user operates one of the first-level menu items, All the data of the second-level submenu to which the current first-level item belongs will be requested to the background through Ajax. If you continue to request an item in the already presented second-level menu, all three data corresponding to the operated second-level menu item will be requested from the backend. All data in the level menu, and so on... In this way, you can get what you use and as much as you need. There will be no redundancy and waste of data, reduce the total amount of data downloaded, and there is no need to reload when updating the page. For all content, only the part that needs to be updated can be updated. Compared with background processing and reloading, the user's waiting time is shortened and the waste of resources is minimized.

In addition, because Ajax can call external data, it can also realize the function of data aggregation (with corresponding authorization of course), such as the BETA version of the online RSS reader just released by Microsoft on March 15; it can also benefit some open data , and developed some of its own applications, such as some novel book search applications using Amazon data.

In short, Ajax is suitable for WEB applications with a lot of interactions, frequent data reading, and good data classification.

1. Reduce the burden on the server. Because the fundamental concept of Ajax is "getting data on demand", it can reduce the burden caused by redundant requests and impacts on the server to the greatest extent;

2. Update the page without refreshing, reducing the user's actual and psychological waiting time;

First of all, the "data on demand" model reduces the actual amount of data read. To give a very vivid analogy, if the way of overloading is to return to the origin from one end point and then to another end point, then Ajax is based on One end point is the base point to reach the other end point;

Secondly, even if you want to read relatively large data, you don’t have to have a white screen like RELOAD. Since Ajax uses XMLHTTP to send requests to get server response data, you can use Javascript to operate the DOM without reloading the entire page. The page is finally updated, so during the process of reading data, the user is not faced with a white screen, but the original page status (or a LOADING prompt box can be added to let the user understand the status of data reading), only The content of the corresponding part is updated only after all the data is received, and this update is also instantaneous and can hardly be felt by the user. In short, users are very sensitive. They can feel your consideration for them. Although it is unlikely to have immediate results, it will accumulate their dependence on the website bit by bit in the hearts of users.

3. Better user experience;

4. You can also transfer some of the previous work burdened by the server to the client, which is beneficial to the client’s idle processing power, reducing the burden on the server and bandwidth, saving space and bandwidth Rental cost;

5. Ajax can call external data;

6. It is based on standardized and widely supported technologies and does not require plug-ins or downloaded applets;

7. Ajax separates the interface and application in the WEB (It can also be said to be the separation of data and presentation);

8. It is a double win for users and ISPs.

6. Problems with Ajax

1. Some handheld devices (such as mobile phones, PDAs, etc.) currently do not support Ajax very well;

2. Ajax engines made with JavaScript, JavaScript compatibility and DeBug are all problems. A headache for people;

3. Ajax’s non-refresh reload, because the changes in the page are not as obvious as the refresh reload, so it is easy to cause trouble to users - users are not sure whether the current data is new or has been updated. The existing solutions include: prompting at relevant locations, designing the data update area to be more obvious, prompting the user after the data is updated, etc.;

4. The support for streaming media is not as good as FLASH and Java Applet;

The above is Ajax Program design, For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn