Application of Ajax technology to develop "back" button problems

Source: Internet
Author: User
Tags object error handling header html page http request string version access
ajax| Button | program | problem

First, Introduction

AJAX, an acronym for Asynchronous JavaScript and XML, is the latest technical word. Asynchrony means that you can send a request to a server via Hypertext Transfer Protocol (HTTP) and continue processing additional data while waiting for the response.

This means, for example, that you can call a server-side script to retrieve data in XML from a database, send the data to a server in a database, or simply load an XML file to populate your Web site without refreshing the page. However, while this new technology provides great power, it also raises a lot of controversy over the "Back" button issue. This article will help you determine when using AJAX is the best choice in the real world.

First, I assume you have a basic understanding of the acronym JavaScript and XML parts. Although you can request any type of text file via Ajax, I focus on XML here. I will explain how to use Ajax in the real world and how to evaluate its value in a project. After you have finished reading this article, you will understand what Ajax is, in what circumstances, and how and how to use the technology. You will learn how to create objects, make requests, and customize responses while maintaining a visual experience for the user.

I have created an example project that is appropriate for this article. This example implements a simple request-it loads an XML file that contains the content of the page and analyzes the data to display it in an HTML page.

Ii. General properties and methods

Tables 1 and 2 provide an overview of the properties and methods-they are Windows Internet Explorer 5,mozilla,netscape 7,safari 1.2, and table 1 properties

Property Describe
onReadyStateChange The event handler is activated when the request object changes.
ReadyState Returns a value indicating the current state of the object.
ResponseText The version of the response string from the server.
Responsexml A DOM-compliant document object from the response of the server.
Status The status code of the response from the server.
StatusText The status message returned as a string.


Table 2 method

method description
abort ()
getallresponseheaders ()
getresponseheader ("Headerlabel") Retrieves the value of an HTTP header from the response body.
open ("Method", "URL" [, asyncflag[, "UserName" [, "Password"]])
send (content)
setrequestheader ("label", "value") Specifies the name of an HTTP header.


third, where to start

First, you need to create the XML file-we will request it later and analyze it as the page content. The file you are requesting must reside on the same server as the target project.

Next, create the HTML file that makes the request. The request occurs when the page is loaded by using the OnLoad method in the page body. Next, the file requires an ID div tag so that we can locate the content when we are ready to display it. When you have finished all of these, the main body of your page looks as follows:







Iv. Creating the Request object

In order to create the request object, you must check whether the browser uses XMLHttpRequest or ActiveXObject. The main difference between the two objects is the use of their browsers. Windows IE version 5 and above use ActiveX objects, while Mozilla,netscape 7,opera and Safari 1.2 and above use XMLHttpRequest objects. Another difference is the way you create objects: Opera,mozilla,netscape and Safari allow you to simply invoke the object's constructor, but Windows IE needs to pass the object's name to the ActiveX constructor. Here's an example of how to create code to decide which object to use and how to create it:

if (window. XMLHttpRequest)

{request = new XMLHttpRequest ();}

else if (window. ActiveXObject)

{request = new ActiveXObject ("MSXML2.") XMLHTTP ");}

V. Issue of requests

Now that you have created your request, you are ready to send a request to the server. Create a reference to the event handler to listen to the onReadyStateChange event. The event handler method will then respond when the state changes. Once we have completed the request, we begin to create this method. Open the connection to get or post a custom url-this is a content.xml and set a Boolean definition-whether you want to make an asynchronous call.

Now it's time to make the request. In this example, I use NULL because we are using get; In order to use post, you need to send a query string using the following method:

Request.onreadystatechange = Onresponse;

Request.open ("get". URL, True);

Request.send (NULL);


vi. customizing loading and error handling messages

The event handler that you create for the onReadyStateChange method is the place to centralize loading and handling errors. It is time to consider the user and provide feedback on the status of the content they interact with. In this instance, I provide feedback for all the Mount status codes and provide some basic feedback on the most frequently occurring error-handling status codes. To display the current state of the request object, the ReadyState property includes some values that appear in the following table.

Value Describe
0 Uninitialized, the object is not initialized with data.
1 In the mount, the object is loading its data.
2 The load ends, and the object completes the load of its data.
3 Can interact, and the user can interact with the object, although it has not yet finished loading.
4 Completed, the object has been completely initialized.


There is a long list of definitions of HTTP status codes in the consortium. I have selected two status codes:

• 200: The request succeeded.

• 404: The server did not find anything that matched the requested file.

Finally, I check any other status code-they will generate an error and provide a generic error message. Here is a code example-you can use it to handle these situations. Notice that I'm locating the div ID that we created earlier in the body of the HTML file and applying mount and/or error information to it-through the innerHTML method-this method is used to set the HTML between the start and end tags of the div object:

if (obj.readystate = 0)

{document.getElementById (' Copy '). InnerHTML = "Sending Request ...";}

if (obj.readystate = 1)

{document.getElementById (' Copy '). InnerHTML = "Loading Response ...";}

if (obj.readystate = 2)

{document.getElementById (' Copy '). InnerHTML = "Response Loaded ...";}

if (obj.readystate = 3)

{document.getElementById (' Copy '). InnerHTML = "Response Ready ...";}

if (obj.readystate = = 4) {

if (Obj.status = =) {return true;}

else if (Obj.status = 404)

{

Add a custom message or redirect the user to another page

document.getElementById (' Copy '). InnerHTML = "File not Found";

}

Else

{document.getElementById (' Copy '). InnerHTML = "There was a problem retrieving the XML.";}

}


When the status code is 200, this means that the request was successful. The following starts with a response.

VII. Analysis and Response

When you are ready to analyze the response from the requesting object, the real work begins. Now you can start working with the data you requested. For testing purposes only, you can use the ResponseText and Responsexml properties to display the raw data from the response during development. To access the nodes in the XML response, first use the request object you created, navigate to the Responsexml attribute to retrieve (you may have guessed) the XML from the response. Navigate to documentelement-It retrieves a reference to the root node of the XML response.

var response = Request.responseXML.documentElement;


Now that you have a reference to the root node of the response, you can use getElementsByTagName () to retrieve the ChildNodes with the node name. The following line uses a nodename of the head to locate a childnode:

Response.getelementsbytagname (' header ') [0].firstchild.data;


Using Firstchild.data allows you to access the text in that element:

Response.getelementsbytagname (' header ') [0].firstchild.data;


Here's a complete example of how to create this code:

var response = Request.responseXML.documentElement;

var header = Response.getelementsbytagname (' header ') [0].firstchild.data;

document.getElementById (' Copy '). InnerHTML = header;


viii. Demand Analysis

Now that you know how to use Ajax basics, the next step is to decide whether to use it in a project. The most important thing to remember is that you can't use the back button when you haven't refreshed the page yet. To do this, you can focus on a small part of your project-it can benefit from using this type of interaction. For example, you can create a form-it queries a script for real-time validation whenever a user enters an input field or a letter. You can create a drag-and-drop page-When you release an item, it can send the data to a script and save the page's state to a database. There is no doubt that the reasons for using AJAX exist, and this use is beneficial to both developers and users, depending on the specific conditions and performance.

There are other ways to solve the "back" button, such as using Google gmail-, which can now provide an undo function for your actions without refreshing the page. There will be many more creative examples-they will bring greater benefits to users by providing them with the tools to create a unique, real-time experience.

Ix. Conclusion

While Ajax allows us to build new and improved ways to interact with a Web page, as a developer, we need to keep in mind that the product is not technology-focused on the user and how it interacts with the user. Without a user base, the project we build is useless. Based on this standard, we can evaluate what technologies should be used and when to use them to create applications that are useful to the appropriate users.



Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.