Mastering Ajax, Part 1th: Introduction to Ajax Primer

Source: Internet
Author: User
Tags html form object serialization


Go: http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html mastering Ajax, Part 1th: Introduction to Ajax Primer


Understanding Ajax and how it works, an effective way to build a website



Ajax is made up of HTML, JavaScript™ technology, DHTML, and DOM, an excellent way to turn a clumsy Web interface into an interactive Ajax application. The author of this series is an Ajax expert who demonstrates how these technologies work together-from a general overview to a discussion of details-to make efficient WEB development a reality. He also unveiled the mysteries of the core Ajax concept, including XMLHttpRequest objects.



See more in this series | 15 Reviews:



Brett McLaughlin ([email protected]), author, editor, O ' Reilly Media Inc.



January 04, 2006


    • Content


Develop and deploy your next application on the IBM Bluemix cloud platform.



Get started with your trial



Five years ago, if you did not know XML, you were an ugly duckling that nobody attached to. 18 months ago, Ruby became the center of attention and did not know that Ruby programmers had to be on the bench. Today, if you want to keep up with the latest technology fashion, your goal is Ajax.



But Ajax is not just a fad, it's a powerful way to build a website, and it's not as difficult as learning a new language.



Visit the Ajax Technology Resource Center, a one-stop center for information about the AJAX programming model, including many documents, tutorials, forums, blogs, wikis, and news. Any new information can be found here.



But before we go into the details of what Ajax is, let's take a few minutes to understand what Ajax does . Currently, there are two basic options for writing an application:


    • Desktop applications
    • WEB Application


The two are similar, and desktop applications are typically CD-based (sometimes downloadable from a Web site) and fully installed on your computer. Desktop applications may use the Internet to download updates, but the code that runs these applications is on the desktop computer. The Web application runs somewhere on the Web server--not surprisingly, to access the application through a Web browser.



However, what's more important than where the running code for these applications is is how the application works and how it interacts with it. Desktop applications are generally very fast (running on your computer without waiting for an internet connection), with a nice user interface (usually related to the operating system) and extraordinary dynamics. You can click, select, enter, open menus and submenus, cruise around, and basically don't have to wait.



Web applications, on the other hand, are the latest trends that provide services that cannot be implemented on the desktop (such as Amazon.com and EBay). However, with the powerful Web there is waiting, waiting for the server to respond, waiting for the screen to refresh, waiting for the request to return and generate a new page.



This is clearly said to be abbreviated, but the basic concept is the same. As you might have guessed, Ajax tries to build a bridge between the functionality and interactivity of desktop applications and the ever-evolving WEB application. You can use dynamic user interfaces and nice controls that are common in desktop applications, but in WEB applications.



What are you waiting for? Let's look at how Ajax transforms a clumsy Web interface into an AJAX application that can respond quickly.


Old technology, New tricks


When it comes to Ajax, there are actually multiple technologies involved, and the flexibility to use it requires a deep understanding of these different technologies (the first few articles in this series will discuss these technologies separately). The good news is that you may already be familiar with most of these techniques, and better yet, these techniques are easy to learn and not as difficult as a complete programming language (such as Java or Ruby).


Definition of Ajax


By the way, Ajax is an abbreviation for asynchronous JavaScript and XML (and DHTML, etc.). This phrase was invented by Jesse James Garrett of Adaptive Path (see Resources), which, according to Jesse's explanation, is not an acronym.



The following are the basic techniques used by AJAX applications:


    • HTML is used to establish WEB forms and to determine the fields used by other parts of the application.
    • JavaScript code is the core code that runs Ajax applications, helping to improve communication with server applications.
    • DHTML or dynamic HTML, which is used to dynamically update the form. We will usediv,spanand other dynamic HTML elements to tag the HTML.
    • The Document Object Model DOM is used (through JavaScript code) to process the HTML structure and (in some cases) the XML returned by the server.


We are here to further analyze the responsibilities of these technologies. I'll delve into these techniques in a future article, so just be familiar with these components and techniques. The more familiar the code is, the easier it will be to shift from a fragmented understanding of these technologies to truly mastering these technologies (and really opening the door to WEB application development).


XMLHttpRequest Object


One of the objects you want to know is probably the most unfamiliar to you, tooXMLHttpRequest. This is a JavaScript object and it is simple to create the object, as shown in Listing 1.


Listing 1. Create a new XMLHttpRequest object
<script language="javascript" type="text/javascript">
var xmlHttp = new XMLHttpRequest();
</script>


This object will be discussed further in the next installment, and now you know that this is the object that handles all server traffic. Before you continue reading, stop and think aboutXMLHttpRequestit: JavaScript is the object of conversation with the server. This is not a generic application flow, which is exactly the source of the powerful features of Ajax.



In a generic WEB application, users fill Out form fields and click the Submit button. The entire form is then sent to the server, the server forwards it to the script that handles the form (usually PHP or Java, or it could be a CGI process or something like that), and the script executes and then sends it back to the new page. The page might be HTML with a new form 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 a new form. The screen becomes blank until the server returns data and then redraws. This is why interactivity is poor, and users don't get immediate feedback, so they feel different from desktop applications.



Ajax basically puts JavaScript technology andXMLHttpRequestobjects between Web forms and servers. When a user fills out a form, the data is sent to some JavaScript code instead of being sent directly to the server. Instead, the JavaScript code captures the form data and sends the request to the server. Also, the form on the user's screen does not blink, disappear, or delay. In other words, the JavaScript code sends the request behind the scenes, and the user doesn't even know that the request was made. Better yet, the request is sent asynchronously, meaning that the JavaScript code (and the user) does not wait for the server to respond. So users can continue to enter data, scroll the screen, and use the application.



The server then returns the data to the JavaScript code (still in the Web form), which determines how the data is processed. It can quickly update form data, making it feel that the application is done immediately, that the form is not committed or refreshed, and that the user gets new data. JavaScript code can even perform some sort of calculation on the received data and send another request without user intervention at all! This is whereXMLHttpRequestthe power is. It can interact with the server as needed, and users can even be completely unaware of what is 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


After the resulting handleXMLHttpRequest, the other 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: It is also easy to update the form, from setting the field value to quickly replacing the image.
    • Parse HTML and XML: Manipulate the DOM using JavaScript code (see the next section) to work with the structure of the XML data returned by the HTML form server.


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


Listing 2. Capturing and setting field values with JavaScript code
// 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 is no special place to pay attention to, it's great! You should realize that there are no very complex things here. As long asXMLHttpRequestyou know, the rest of the Ajax application is the simple JavaScript code shown in Listing 2, mixed with a small amount of HTML. Also, use a little DOM, and we'll take a look at it.


End With DOM


Finally, there is the DOM, the Document Object model. Perhaps the DOM is a bit daunting for some readers, and the HTML designer seldom uses it, even if the JavaScript programmer doesn't use it, unless it's done with a high-end programming task. The use of DOM in a large number of complex Java and C + + programs is probably why Dom is considered difficult to learn.



Fortunately, using the DOM in JavaScript technology is easy and intuitive. Now, as usual, you might want to explain how to use the DOM, or at least some sample code, but that might also mislead you. Even if you ignore the DOM, you can still delve into Ajax, which is the approach I'm going to take. Future articles will discuss Dom again, and now just know that you might need the DOM. When it comes to passing XML and changing HTML forms between the JavaScript code and the server, we delve into the DOM. You can do some interesting work without it, so put the DOM aside now.



Back to top of page


Get the Request object


With the basics above, let's take a look at some concrete examples.XMLHttpRequestis at the heart of Ajax applications and may be unfamiliar to many readers, let's start here. As you can see from listing 1, creating and using this object is very simple, isn't it? Wait a minute.



Remember those nasty browser wars years ago? There is no one thing that gets the same result on a different browser. Whether you believe it or not, these wars are still going on, albeit on a smaller scale. But strangely enough,XMLHttpRequestit became one of the victims of the war. ThereforeXMLHttpRequest, it may be necessary to take different methods for acquiring objects. I'll explain it in more detail below.


Using Microsoft Browser


Microsoft Browser Internet Explorer uses the MSXML parser to process XML (you can learn more about MSXML through resources). So if you're writing an AJAX application that's dealing with Internet Explorer, you have to create the object in a special way.



But not so simple. Depending on the version of JavaScript technology installed in Internet Explorer, MSXML actually has two different versions, so you must write the code separately for both cases. See listing 3, where the code was created on a Microsoft browserXMLHttpRequest.


Listing 3. Create a XMLHttpRequest object on a Microsoft browser
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 the code, but it doesn't matter. At the end of this series of articles, you will have a deeper understanding of JavaScript programming, error handling, conditional compilation, and so on. Now just remember the two lines of code firmly:



xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");



And



xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");。



These two lines of code basically attempt to create an object using one version of MSXML, and if it fails, the object is created with another version. Isn't that good? If none are successful, set thexmlHttpvariable to False to tell you that the code is having problems. If this is the case, it may be because a non-Microsoft browser is installed that requires different code.


Working with Mozilla and non-Microsoft browsers


If you choose a browser other than Internet Explorer, or write code for a non-Microsoft browser, you need to use different code. In fact, this is the simple line of code shown in Listing 1:



var xmlHttp = new XMLHttpRequest object;。



This is a much simpler code to create objects in Mozilla, Firefox, Safari, Opera, and virtually all non-Microsoft browsers that support Ajax in any form or mannerXMLHttpRequest.


Combined.


The key is to support all browsers. Who wants to write an application that can be used only for Internet Explorer or non-Microsoft browsers? Or worse, write an application two times? Of course not! Therefore, the code supports both Internet Explorer and non-Microsoft browsers. Listing 4 shows this code.


Listing 4. Create XMLHttpRequest objects in a way that supports multiple browsers
/* 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();
}


Now, regardless of the strange symbols that are commented out, for example@cc_on, this is a special JavaScript compiler command that will beXMLHttpRequestdiscussed in detail in the next installment of the article. The core of this code is divided into three steps:


    1. Create a variablexmlHttpto refer to the object you are about to createXMLHttpRequest.
    2. Try to create the object in a Microsoft browser:
      • Try toMsxml2.XMLHTTPcreate it using an object.
      • If it fails, try theMicrosoft.XMLHTTPobject again.
    3. If it is still not establishedxmlHttp, the object is created in a non-Microsoft manner.


Finally, youxmlHttpshould refer to a validXMLHttpRequestobject regardless of what browser you are running.


A little description of security


What about security? Browsers now allow users to increase their level of security, turn off JavaScript technology, and disable any options in the browser. In this case, the code will not work anyway. The problem must be dealt with properly at this point, which needs to be discussed in a separate article, to be put in the future (is this series long enough?) Don't worry, you may have mastered it before you finish reading it. Writing a robust but not perfect code now is good for mastering Ajax. We will discuss more details in the future.



Back to top of page


Request/Response in the Ajax world


Now that we have introduced Ajax, weXMLHttpRequesthave a basic understanding of the object and how to create it. If you read carefully, you may already know that you are dealing with a WEB application on a server that is JavaScript technology, rather than an HTML form that is submitted directly to that application.



What is missing? Exactly how to use itXMLHttpRequest. Because this code is very important, every ajax application you write is going to use it in some form, first look at the basic request/response model of Ajax.


Make a request


You already have a brand newXMLHttpRequestobject, now let it do some work. First, you need a JavaScript method that the Web page can invoke (such as when the user enters text or selects an item from the menu). The next step is basically the same process in all Ajax applications:


    1. Get the data you want from your Web form.
    2. Establish the URL to connect to.
    3. Open the connection to the server.
    4. Sets the function to run after the server finishes.
    5. Send the request.


The example Ajax method in Listing 5 is organized in this order:


Listing 5. Make an Ajax request
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 has a clear meaning. The starting code uses the basic JavaScript code to get the values of several form fields. Then set a PHP script as the target of the link. To notice how the script URL is specified, city and state (from the form) are appended to the URL with a simple GET parameter.



Then open a connection, which is the first time you see the useXMLHttpRequest. It specifies the connection method (GET) and the URL to connect to. The last parameter, if settrue, will request an asynchronous connection (this is the origin of Ajax). If usedfalse, the code will wait for the response returned by the server after making a request. If set totrue, the user can still use the form (or even call other JavaScript methods) when the server processes the request in the background.



xmlHttp(Remember, this is aXMLHttpRequestproperty of an object instance) thatonreadystatechangetells the server what to do when it finishes running (it might take five minutes or five hours). Because the code does not wait 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 namedupdatePage()method is triggered.



Finally, a valuenullcall is usedsend(). Since the data to be sent to the server has been added to the request URL (city and state), no data is sent in the request. This makes a request and the server works according to your requirements.



If you don't find anything new, you should realize how simple and straightforward it is! In addition to remembering the asynchronous nature of Ajax, these things are pretty straightforward. Be thankful that Ajax allows you to concentrate on writing beautiful applications and interfaces without worrying about complex HTTP request/response codes.



The code in Listing 5 illustrates the ease of use of Ajax. The data is simple text and can be used as part of the request URL. Send a request with a GET instead of a more complex POST. There is no data to be sent in the request body without XML and the content header to be added; in other words, this is the utopia of Ajax.



Don't worry, things are going to get more complicated as this series of articles unfolds. You'll see how to send a POST request, how to set the request header and content type, how to encode the XML in the message, how to increase the security of the request, and many more things you can do! For the time being, don't worry about the difficulties, master the basic things on the line, and soon we will build a set of Ajax tool Library.


Handling Responses


Now it's time to face the server's response. Now just know two points:


    • Don't do anything untilxmlHttp.readyStatethe value of the property equals 4.
    • The server fills in the response into thexmlHttp.responseTextproperty.


The 1th, the ready state, will be discussed in more detail in the next article, and you will learn more about the phase of the HTTP request than you might have imagined. Now just check for a specific value (4) (more values are available in the next installment). 2nd, usingxmlHttp.responseTextattributes to get the server's response is simple. The example method in Listing 6 is available for the server to call based on the data sent in Listing 5.


Listing 6. Handling Server Responses
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 using the value returned by the server (here is the ZIP code of the city and state entered by the user). Then the field containing the ZIP codezipCodesuddenly appeared, and the user did not press any button ! That's what the desktop app feels like before. Fast response, dynamic feel, and so on, all because of a small piece of Ajax code.



The attentive reader may notice thatzipCodeit is an ordinary text field. Once the server returns a ZIP code, theupdatePage()method uses the city/State ZIP code to set the value of that field, which the user can override. There are two reasons to do this: Keep the example simple, stating that sometimes you might want users to be able to modify the data returned by the server. To remember these two points, they are important for good user interface design.



Back to top of page


Connect Web Forms


What else is there? Not much, actually. A JavaScript method captures the user's input form information and sends it to the server, another JavaScript method listens and processes the response, and sets the value of the field when the response returns. All of this actually relies on invoking the first JavaScript method, which starts the whole process. The most obvious way is to add a button to the HTML form, but this is the 2001 approach, don't you think? Use JavaScript technology like Listing 7.


Listing 7. Start an Ajax process
<form>
 <p>City: <input type="text" name="city" id="city" size="25" onChange="callServer();" /></p>
 <p>State: <input type="text" name="state" id="state" size="25" onChange="callServer();" /></p>
 <p>Zip Code: <input type="text" name="zipCode" id="city" size="5" /></p>
</form>


If it feels like a fairly common code, that's right, that's it! When the user enters a new value in the City or state field, thecallServer()method is triggered, and Ajax starts to run. Kinda understand what's going on? All right, that's it!



Back to top of page


Conclusion


Now you're probably ready to start writing your first Ajax application, or at least want to read the articles in resources? But you can start with a basic idea of how these applications work andXMLHttpRequesthave a basic understanding of the objects. In the next installment, you'll learn how to handle JavaScript and server communication, how to use HTML forms, and how to get DOM handles.



Now take some time to think about how powerful Ajax applications are. Imagine how a Web form responds immediately when you click a button, enter a field, select an option from a combo box, or drag a mouse over the screen. Think about what it means to be asynchronous , think of the JavaScript code running and not wait for the server to respond to its request. What kind of problems will you encounter? What kind of field will it enter? Given this new approach, how do you change the design of a form when programming?



If you spend a bit of time on these issues, you'll get more revenue than simply cutting/pasting some code into an application that you don't understand at all. In the next installment, we'll put these concepts into practice, detailing the code needed to make the application work in this way. So, let's enjoy the possibilities of Ajax now.


Reference Learning
  • You can refer to the original English text on the DeveloperWorks global site in this article.
  • You can refer to other articles in this series.
  • Ajax Technology Resource Center: All the questions about Ajax on DeveloperWorks can be found here.
  • Adaptive Path is a leading user interface design company that can read more about Ajax by carefully reading their website.
  • If you care about the origin of the word Ajax, see Jesse James Garrett and his Ajax articles (such as this one).
  • Before you can understand the subject object of the next issueXMLHttpRequest, read the Using the XML HTTP Request object article.
  • If you use Internet Explorer, you can access the XML Developer Center for Microsoft Developer Network.
  • Ajax for Java developers: Building dynamic Java Applications (developerworks,2005 September) describes this innovative approach, which solves the page Reload challenge and creates a dynamic WEB application experience.
  • Java object Serialization for Java Developer Ajax:ajax (developerworks,2005 October) describes five ways to serialize data in an Ajax application.
  • Using AJAX with PHP and Sajax, the Simple AJAX Toolkit integrates server-side PHP with JavaScript (developerworks,2006 May), a tutorial for people who are interested in developing a rich Web application, with Ajax and PHP dynamic update content.
  • Call the SOAP Web service using AJAX, part 1th: Building a Web Services Client (developerworks,2006 January) describes how to implement a Web browser-based SOAP Web service client using AJAX design patterns.
  • XML problem: Beyond DOM (developerworks,2005 May) details how to use the Document Object model to build dynamic WEB applications.
  • Building Applications using Ajax: Learning to build Web applications that support real-time validation with Ajax (developerworks,2006 March) demonstrates how to construct Web applications that support real-time verification using Ajax.
  • Ajax for Java developers: using AJAX in conjunction with Direct Web Remoting (developerworks,2005 November) demonstrates how to automate the tedious details of Ajax.
  • OSA Foundation has a wiki that investigates the Ajax/javascript library.
  • The object reference section of XUL Planet details the XMLHttpRequest objects (not to mention the various other XML objects, such as DOM, CSS, HTML, Web Service, and Windows and Navigation objects).
  • Take a look at some of the great Ajax applications shown on flickr.com.
  • Google's GMail is another example of a revolutionary WEB application that exploits Ajax.
  • Head Rush Ajax (O ' Reilly Media, inc.,2006 February) contains the article as well as the content described in this series (and more), and employs the innovative award-winning format Head first.
  • javascript:the DefinitiveGuide, 4th edition (O ' Reilly Media, inc.,2001 November) is a great source of information about JavaScript and the use of dynamic Web pages.
  • DeveloperWorks China website web Development Zone specifically publishes articles on a variety of web-based solutions.
Discuss
    • Participate in forum discussions.
    • Ajax.NET Professional is a good blog about all aspects of Ajax.
    • Join the DeveloperWorks community by participating in the DeveloperWorks blog.


Mastering Ajax, Part 1th: Introduction to Ajax Primer


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.