Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to getting started with AJAX

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "introduction to AJAX", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn the "introduction to AJAX" this article.

1. What is AJAX?

The full name of AJAX is asynchronous JavaScript and XML, which is the abbreviation of Asynchronous JavaScript and XML. AJAX technology is used to create interactive web applications for website development, as for what is asynchronous, will be explained later.

1.1 Desktop applications and Web applications

Before discussing AJAX technology in detail, you need to know exactly what AJAX technology is for. Currently, there are two basic types of writing applications:

Desktop applications (Desktop Application)

Web Application (Web Application)

Desktop applications can be obtained from the Internet or as CD, and need to run on desktop computers, such as some of our common PC software. Unlike Web applications, Web applications are run on a Web server somewhere, so they need to be accessed through a Web browser.

More important than where the code for these applications runs, however, is how the application works and how it interacts with it. Desktop applications are generally fast, have beautiful user interfaces and extraordinary dynamics, and can click, select, open menus and submenus, and cruise around without waiting; on the other hand, Web applications (such as Amazon.com and eBay) provide services that desktop programs cannot achieve. However, with the power of Web comes waiting, waiting for a response from the server, waiting for the screen to refresh, waiting for the request to return, and generating a new interface.

The emergence of AJAX is to alleviate the problem of waiting in Web applications compared with desktop applications.

1.2 AJAX-old technology, new face

AJAX technology is not really a new technology, but an integration of several other existing technologies.

AJAX applications use the following basic technologies:

Use HTML and CSS to create Web forms and represent web page information

Use JavaScript to operate DOM (Document Object Model) for dynamic display and interaction

Use XMLHttpRequest object to exchange data with Web server asynchronously

Use XML for data exchange and related operations

Use JavaScript to tie everything together.

Let's further analyze the responsibilities of these technologies. At present, I just need to be familiar with these components and technologies. The more familiar you are with this code, the easier it is to move from a piecemeal understanding of these technologies to a real grasp of them (while also really opening the door to Web application development).

XMLHttpRequest object

The one object you want to know is probably the strangest to you: XMLHttpRequest. This is a JavaScript object, which is easy to create, as shown in listing 1.

Listing 1. Create a new XMLHttpRequest object

The copy code is as follows:

You'll learn more about this object later, knowing that this is the object that handles all server communications. Before you move on, stop and think: it's JavaScript technology that talks to the server through the XMLHttpRequest object. This is no ordinary application flow, which is precisely the source of the power of Ajax.

In a normal Web application, the user fills out the form field and clicks the submit button. The entire form is then sent to the server, which forwards it to the script that processes the form (usually a PHP or Java, or maybe a CGI process or something like that), and when the script is executed, it is sent back to a new page. The page may be a HTML with a new form that has been populated with some data, a confirmation page, or a page with some options selected based on the data entered in the original form. Of course, the user must wait while the script or program on the server processes and returns the new form. The screen goes blank and waits for the server to return data before redrawing. This is the reason for the poor interactivity, and users don't get immediate feedback, so they feel different from desktop applications.

Ajax basically puts JavaScript technology and XMLHttpRequest objects between the Web form and the server. When the user fills out the form, the data is sent to some JavaScript code rather than directly to the server. Instead, the JavaScript code captures form data and sends a request to the server. At the same time, the form on the user's screen does not flicker, disappear, or delay. In other words, the JavaScript code sends the request behind the scenes, and the user doesn't even know it was made. Better yet, the request is sent asynchronously, meaning that the JavaScript code (and the user) does not have to wait for a response from the server. So users can continue to enter data, scroll through the screen, and use the application.

The server then returns the data to the JavaScript code (still in the Web form), which decides what to do with the data. It can update the form data quickly, giving the impression that the application is completed immediately, the form is not submitted or refreshed, and the user gets the new data. JavaScript code can even perform some calculation on the received data and send another request without user intervention at all! This is the power of XMLHttpRequest. It can interact with the server on its own as needed, and users can even be completely unaware of what's going on behind the scenes. The result is a dynamic, responsive, highly interactive experience similar to desktop applications, but with all the power of the Internet behind it.

Add some JavaScript

Once you get the handle to XMLHttpRequest, the rest of the JavaScript code is very simple. In fact, we will use JavaScript code to accomplish very basic tasks:

Get form data: JavaScript code can easily extract data from an HTML form and send it to the server.

Modify the data on the form: updating the form is also simple, such as setting field values or quickly replacing images.

Parsing HTML and XML: manipulate DOM using JavaScript code to handle the structure of XML data returned by the HTML form server.

For the first two points, you need to be very familiar with the getElementById () method, as shown in listing 2.

Listing 2. Capture and set field values with JavaScript code

The copy code is as follows:

/ / Get the value of the "phone" field and stuff it in a variable called phone

Var phone = document.getElementById ("phone") .value

/ / Set some values on a form using an array called response

Document.getElementById ("order"). Value = response [0]

Document.getElementById ("address"). Value = response [1]

There's nothing special to pay attention to here. It's great! You should realize that there is nothing very complicated here. Once you have mastered the rest of the XMLHttpRequest,Ajax application, you will have the simple JavaScript code shown in listing 2, mixed with a small amount of HTML.

2. What are the advantages and disadvantages of AJAX?

2.1 benefits of AJAX

The biggest advantage of using AJAX is that you can maintain data without updating the entire page. This allows Web applications to respond more quickly to user requests, improving the user experience while avoiding sending messages that have not changed on the network.

Traditional Web applications allow the client to fill out a form (form) and send a request to the Web server when the form is sent. The server receives and processes the incoming form and sends it back to a new web page, but this wastes a lot of bandwidth, because most of the HTML code is often the same in front and back of the two pages that process feedback. Because each application communication needs to send a request to the server, the response time of the application depends on the response time of the server for a long time, which causes the response of the user interface to be much slower than that of the local application.

In contrast, the AJAX application can only send and retrieve the necessary data to the server, it uses SOAP or some other XML-based page service interface (interface), and uses JavaScript on the client side to process the response from the server. Because there is a significant reduction in the amount of data exchanged between the server and the browser (about 5% of the original), as a result, we can see faster applications (results). At the same time, a lot of processing work can be done on the client machine that made the request, so the processing time of the Web server is also reduced.

2.2 disadvantages of AJAX

The main criticism of AJAX is that it may disrupt the normal behavior of the browser's back button. In the case of dynamically updating the page, the user cannot return to the state of the previous page because the browser can only record static pages in the history. The difference between a fully read page and a dynamically modified page is subtle: users usually want to click the back button to cancel their previous operation, but on AJAX pages, it may not be possible to do so. However, developers have come up with a variety of ways to solve this problem, most of which reproduce changes on the page by creating or using a hidden IFRAME when the user clicks the back button to access the history. (for example, when the user clicks back in Google Maps, it searches in a hidden IFRAME and then reflects the search results on the AJAX element to restore the application state to its current state. )

Another related view is that using dynamic page updates makes it difficult for users to save a particular state to their favorites. Solutions to this problem have also emerged, most of which use URL fragment identifiers (often referred to as anchor points, that is, the part after # in the URL) to keep track, allowing the user to return to a specified application state. Many browsers allow JavaScript to update anchors dynamically, which enables Ajax applications to update anchors while updating the display. This solution also resolves a lot of arguments about not supporting the back button

When developing AJAX, network latency-- the interval between a user's request and the server's response-- needs to be carefully considered. Not giving users a clear response, not properly pre-reading data, or improper handling of XMLHttpRequest can delay users, which users do not want to see and do not understand. The usual solution is to use a visual component to tell the user that the system is operating in the background and is reading data and content.

3. General process of AJAX application

3.1Creating request objects

With the basics above, let's take a look at some specific examples. XMLHttpRequest is at the heart of AJAX applications and may be unfamiliar to many readers, so let's start here. As you can see from listing 1, it's very easy to create and use this object, isn't it? Hold on.

Remember those pesky browser wars a few years ago? Nothing gets the same result on different browsers. Believe it or not, these wars continue, albeit on a smaller scale. But unfortunately, XMLHttpRequest became one of the victims of this war. So getting the XMLHttpRequest object may require a different approach. I will explain it in detail below.

Use the Microsoft browser

The Microsoft browser Internet Explorer uses the MSXML parser to process XML. So if you write an AJAX application that deals with Internet Explorer, you must create objects in a special way.

But it's not that simple. Depending on the version of JavaScript technology installed in Internet Explorer, there are actually two different versions of MSXML, so you have to write code for both cases. See listing 3, where the code creates a XMLHttpRequest on the Microsoft browser.

Listing 3. Create a XMLHttpRequest object on a Microsoft browser

The copy code is as follows:

Var xmlHttp = false

Try {

XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP")

} catch (e) {

Try {

XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP")

} catch (e2) {

XmlHttp = false

}

}

You may not fully understand this code, but it doesn't matter, just keep two lines of code in mind:

XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP")

XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP")

These two lines of code basically try to create an object using one version of MSXML and, if it fails, another version. Not bad, huh? If both are unsuccessful, set the xmlHttp variable to false to tell your code that there is a problem. If this happens, it may be because a non-Microsoft browser is installed and different code is required.

Dealing with Mozilla and non-Microsoft browsers

If you choose a browser other than Internet Explorer, or if you write code for a non-Microsoft browser, you need to use different code. It's actually a simple line of code shown in listing 1:

Var xmlHttp = new XMLHttpRequest object;.

This much simpler line of code creates a XMLHttpRequest object in Mozilla, Firefox, Safari, Opera, and almost all non-Microsoft browsers that support Ajax in any form or manner.

A general approach across browsers

The key is to support all browsers. Who wants to write an application that works only with Internet Explorer or non-Microsoft browsers? Or worse, write an application twice? Certainly not! So the code should support both Internet Explorer and non-Microsoft browsers. Listing 4 shows such code.

Listing 4. Create XMLHttpRequest objects in a way that supports multiple browsers

The copy code is as follows:

/ * Create a new XMLHttpRequest object to talk to the Web server * /

Var xmlHttp = false

/ * @ cc_on @ * /

/ * @ if (@ _ jscript_version > = 5)

Try {

XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP")

} catch (e) {

Try {

XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP")

} catch (e2) {

XmlHttp = false

}

}

@ end @ * /

If (! xmlHttp & & typeof XMLHttpRequest! = 'undefined') {

XmlHttp = new XMLHttpRequest ()

}

For now, forget about the strange symbols that are commented out, such as @ cc_on, which is a special JavaScript compiler command that will be discussed in detail in the next article on XMLHttpRequest. The core of this code is divided into three steps:

Create a variable xmlHttp to refer to the XMLHttpRequest object you are about to create.

Try to create the object in the Microsoft browser:

Try to create it using the Msxml2.XMLHTTP object.

If it fails, try the Microsoft.XMLHTTP object again.

If the xmlHttp is still not established, the object is created in a non-Microsoft manner.

Finally, xmlHttp should reference a valid XMLHttpRequest object, no matter what browser you are running.

3.2 client request / server response mechanism of AJAX technology

Now that we've introduced AJAX, we have a basic understanding of the XMLHttpRequest object and how to create it. If you read it carefully, you probably already know that you are dealing with JavaScript technology with the Web application on the server, not the HTML form submitted directly to that application.

What is missing? Exactly how to use XMLHttpRequest. Because this code is so important that every AJAX application you write uses it in some way, let's take a look at what the basic request / response model of AJAX looks like.

Make a request

Now that you have a brand new XMLHttpRequest object, let it do some work. First, you need a JavaScript method that the Web page can call (for example, when the user enters text or selects an item from the menu). Then there is the process that is basically the same in all Ajax applications:

Get the data you need from the Web form.

Establish the URL to connect to.

Open a connection to the server.

Sets the function that the server will run when it is finished.

Send a request.

The example Ajax methods in listing 5 are organized in this order:

Listing 5. Issue an Ajax request

The copy code is as follows:

Function callServer () {

/ / Get the city and state from the web form

Var city = document.getElementById ("city") .value

Var state = document.getElementById ("state") .value

/ / Only go on if there are values for both fields

If ((city = = null) | | (city = = ")) return

If ((state = = null) | | (state = = ")) return

/ / Build the URL to connect to

Var url = "/ scripts/getZipCode.php?city=" + escape (city) + "& state=" + escape (state)

/ / Open a connection to the server

XmlHttp.open ("GET", url, true)

/ / Setup a function for the server to run when it's done

XmlHttp.onreadystatechange = updatePage

/ / Send the request

XmlHttp.send (null)

}

Most of the code is clear. The initial code uses basic JavaScript code to get the values of several form fields. Then set a PHP script as the target of the link. Note how the script URL is specified, with city and state (from the form) appended to the URL using simple GET parameters.

Then open a connection, and this is the first time you've seen using XMLHttpRequest. The connection method (GET) and the URL to be connected are specified. If the last parameter is set to true, an asynchronous connection will be requested (which is where Ajax comes from). If you use false, the code waits for a response from the server after making the request. If set to true, the user can still use the form (or even call other JavaScript methods) when the server processes the request in the background.

The onreadystatechange property of xmlHttp (remember, this is an instance of the XMLHttpRequest object) tells the server what to do after the run is complete (which may take five minutes or five hours). Because the code is not waiting for the server, you must let the server know what to do so that you can respond. In this example, if the server finishes processing the request, a special method called updatePage () will be triggered.

Finally, send () is called with the value null. Because the data to be sent to the server (city and state) has been added to the request URL, no data needs to be sent in the request. The request is made and the server works according to your requirements.

If you don't find anything new, you should realize how simple and clear it is! Apart from keeping in mind the asynchronous nature of AJAX, all of this is fairly simple. You should be grateful to AJAX for allowing you to focus on writing beautiful applications and interfaces without worrying about complex HTTP request / response code.

The code in listing 5 illustrates the ease of use of Ajax. Data is simple text that can be used as part of the request URL. Send the request using GET instead of the more complex POST. There is no XML and content headers to add, and there is no data to send in the request body; in other words, this is the utopia of Ajax.

Don't worry, as this series of articles unfolds, things will become more and more complicated. You'll see how to send a POST request, how to set the request header and content type, how to encode XML in a message, how to increase the security of the request, there's a lot more you can do! Don't worry about the difficulties for the time being, just master the basics, and soon we will build a complete library of Ajax tools.

Process the response

Now it's time to face the server's response. Now you just need to know two things:

Do nothing until the value of the xmlHttp.readyState property equals 4.

The server will populate the response into the xmlHttp.responseText property.

The first of these, the ready state, will be discussed in more detail in the next article, and you will learn more about the stages of HTTP requests than you might think. Now all you have to do is check a specific value (4) (there are more values to be introduced in the next article). Second, use the xmlHttp.responseText attribute to get a response from the server, which is simple. The sample method in listing 6 is available for the server to call based on the data sent in listing 5.

Listing 6. Processing server responses

The copy code is as follows:

Function updatePage () {

If (xmlHttp.readyState = = 4) {

Var response = xmlHttp.responseText

Document.getElementById ("zipCode") .value = response

}

}

The code is neither difficult nor complex. It waits for the server to call and, if it is ready, sets the value of another form field with the value returned by the server (in this case, the ZIP code for the city and state entered by the user). So the zipCode field containing the ZIP code suddenly appears, and the user doesn't press any buttons! This is the feeling of desktop applications mentioned earlier. Quick response, dynamic feeling, and so on, all because of a small piece of Ajax code.

Careful readers may notice that zipCode is an ordinary text field. Once the server returns the ZIP code, the updatePage () method sets the value of that field with the city / state ZIP code, and the user can overwrite the value. There are two reasons for this: keep the example simple, illustrating that you may sometimes want the user to be able to modify the data returned by the server. Keep these two points in mind, they are important for good user interface design.

3.3 [off-topic] how to connect Web forms

What else is there? Actually, there's not much left. One JavaScript method captures the information that the user enters the form and sends it to the server, while the other JavaScript method listens and processes the response and sets the value of the field when the response returns. All of this actually depends on calling the first JavaScript method, which starts the whole process. The most obvious way is to add a button to the HTML form, but that's the way it was in 2001, don't you think? Take advantage of JavaScript technology like listing 7.

Listing 7. Start an Ajax process

The copy code is as follows:

City:

State:

Zip Code:

If it feels like a fairly ordinary piece of code, that's right, exactly! When the user enters a new value in the city or state field, the callServer () method is triggered, and the Ajax starts running. Do you kind of understand what's going on? Okay, that's it!

4. What are the problems in developing AJAX applications? How did you solve it?

For programmers, the biggest headache in developing Ajax applications is the following:

Ajax is essentially a browser-side technology, and the first unavoidable problem is browser compatibility. Different browsers always have different support for JavaScript/DOM/CSS or Bug, and even different versions of the same browser may have different support for JavaScript/DOM/CSS. This causes programmers to spend most of their time writing Ajax applications debugging browser compatibility rather than the application itself.

The main purpose of Ajax technology is to locally exchange data between the client and the server. Like the traditional master-slave architecture, it is inevitable that part of the business logic will be implemented on the client, or partly on the client side on the server. Because the business logic may be distributed between the client and the server and implemented in different programming languages, it makes Ajax applications extremely difficult to maintain. If there is a need to change the user interface or business logic, coupled with the compatibility of the previous JavaScript/DOM/CSS, Ajax applications often become a nightmare for programmers. To solve the problem of decentralized business logic, Ajax development frameworks can be roughly divided into two categories:

Put the business logic and presentation layer in the browser, and the data layer in the server: because all programs are executed in JavaScript on the client side, they only ask the server for services when they need data, which is also known as the fat client (fat client) architecture. Under this architecture, servers are usually only used to provide and store data. The advantage of this method is that programmers can make full use of JavaScript with business logic to make a special user interface to meet the requirements of end users. But there are a lot of problems, the main reason is that, first, the JavaScript language itself may not be able to handle complex business logic. Second, the executive efficiency of JavaScript has always been poor. Third, JavaScript still needs the cooperation of appropriate server-side programs to access server data. Fourth, the problem of browser compatibility arises again. Some Ajax development frameworks such as DWR attempt to avoid compatibility problems by automatically generating JavaScript and opening channels so that JavaScript can directly call server-side Java programs to simplify data access. However, the first and second problems still exist, and the programmer must make considerable effort to meet the specifications of the application, or may not be able to do so at all.

Put the presentation layer, business logic, and data layer on the server, and the browser has only the user interface engine (User Interface engine); this method is also known as the thin client (thin client) architecture, or the central server (server-centric) architecture. The user interface engine of the browser is only used to reflect the performance layer of the server and to convey the user's input back to the performance layer of the server. Events triggered by the browser are also sent back to the server for processing, update the presentation layer according to the business logic, and then reflect it back to the browser. Because all applications are executed on the server, and the data and presentation layer can be accessed directly, programmers only need to use relatively mature programming languages on the server side (such as Java). They no longer need to learn JavaScript/DOM/CSS, and it is relatively easy to develop applications. The disadvantage is that the user interface engine and presentation layer usually exist in the form of standard components, such as the need for special components (user interface), often need to be provided by the developers of the original framework. For example, the open source Ajax development framework ZK currently supports XUL and XHTML components, but does not have the support of XAML.

Ajax submits requirements to the server asynchronously. As far as the server is concerned, it is no different from the traditional form submission requirements, and because it is submitted asynchronously, if there are multiple Ajax requirements and form submission requirements at the same time, there is no guarantee that which requirement will get the response from the server first. This can cause typical racing problems of multiprocess (process) or multithreaded (thread) contention in an application. Programmers therefore have to handle or tamper with JavaScript to avoid such competitive problems (such as disable the button before the Ajax request is answered), which unnecessarily adds to the programmer's burden. It seems that ZK is the only development framework known to handle this issue automatically.

The above is all the contents of this article "introduction to AJAX". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report