Web development under Ajax and XMLHttpRequest

Source: Internet
Author: User

I. Introduction

While XMLHttpRequest objects and Ajax bring huge benefits to users and developers, you may still have some questions you haven't considered-but it's time to draw everyone's attention.

Even annoying people like XMLHttpRequest because it providesProgramFunctions that Members really dream. Because of this new technology, web application software has become similar to desktop applications. Nowadays, the problem is always like "if it is ...... "That's simple. This allows naive end users to know about the server, customer, send back, and submit buttons-" submit? What do I submit? "-A series of problems are freed from the sea.

Countless terrible cases have exploded on the web recently. They fully explain why remote scripts (or "ajax", if you like) it is the greatest thing since the single-pixel GIF technology. In fact, the string of cool and useful application software is growing, as posted by sites such as Flickr, Google maps, and the weborb Presentation Server.

These sites and many other places publicize Ajax capabilities. To be fair, this technology has considerable potential in improving the quality of online operations. However, despite its many advantages, there is still a strange smell in this holy web communication cup; like beer and chocolate that swing in front of us, there is still an evil aspect in it-how pure and naive it looks on the surface.

This potential evil exists in the important functional gaps behind the user's familiar operation interface. Many of you may have been using the Internet for nearly 10 years, and you know how it works: You click around, fill the form, modify your input; when you finish all this, you can click Submit. You all know these excellent experiences-they are transferred from the Internet generation to the new generation, for example: "Do not click the submit button twice-otherwise, the form may have to be submitted twice "or" wait a little longer, it is processing "or" after you submit the form, do not click the 'backward' button ", and so on.

However, since Ajax has become an entry, you can throw the basic knowledge out of the window. It's like "everything is okay"-suddenly there is a new type of Tracked data-it can be sent at any time without the user's understanding, even the user does not know that this may happen. Every one of them is very diligent, very poor, very busy words, very diligent, Huai Yu 6, and sent to the very infected with acne, and then steal the EB server, and you can't do anything about it.

Ii. XMLHttpRequest: Advantages and Disadvantages

Just as many technologies have advantages and disadvantages, the purpose of this technology is to take advantage of its advantages. Until now, XMLHttpRequest has brought so many advantages, such as input verification without rollback, spelling check in the text area, and Gmail. Interfaces created based on AJAX technology are very interesting to use and even more interesting to code. It is hard to believe that such a magical technology can do something wrong.

However, even if no major security vulnerability is found, the XMLHttpRequest may fail due to its external elegance. It is likely to fail in the application of "user profile"-for better description purposes. Currently, the user profile graph helps the web site master detective trend, tracking web browsing habits and helping eliminate usage problems. However, until now, developers can only analyze the returned data-the user decides to make the data obtained by the server happy to be processed after submission.

However, through a microsecond method, this kind of energy balance will be transitioned. By using Ajax technology, a user's behavior can be continuously and carefully monitored. Because it can be done, it will be done; this brings people a considerable headache, it is not just a waste of bandwidth, MB of junk information, or a slower number of web page loads.

Imagine that here is only an example to illustrate the problem. You dropped a newly purchased iPod to the ground and it stopped working. With the idea of a free replacement, you sent an email to Apple's after-sales service department, saying, "I just bought a new iPod. I accidentally dropped it to the stairs and it suddenly stopped working. "Then, you decided to delete the second sentence to support your reasons. It's too late! If the website uses Ajax technology, your reflection may have been killed at your Complaint Desk!

Or-a more malicious and destructive example-consider this situation: Most people have one or two usernames/passwords used for their "unimportant" sites, such as news sites, blogs, and forums. They may also have several reserved combinations for more sensitive websites-banking, Web emails, and work accounts. Inputting incorrect logon details on a given page is a common and easy mistake. Although the effects of their previous habits are primarily responsible for this, people often realize what they are doing before clicking the submit button.

Unfortunately, it is quite troublesome to implement an Ajax key logging program. With such a key logging program, you can useCodeTo collect incorrect login attempts, and then conduct a test on a series of "important" sites-of course, XMLHttpRequest objects can also be used.

Iii. Malicious suggestion

To be fair, most of the "malicious" applications referenced above can be reasonably handled, even before the emergence of XMLHttpRequest technology. Indeed, the request object is a more elegant method for successfully submitting form data than the previous IFRAME technology. However, XMLHttpRequest works in a more natural way, which can make the interaction between the client and the server disappear.

It is ironic that, with the popularity of Firefox Web browsers, many users have learned the depth and breadth of information that can be stored and controlled by web clients. With the widespread adoption of tools such as greasemonkey, Web Developer extensions, and cookie editors, people are more confident than ever that if the problem occurs on the client, the responsibility is generally attributed to the user.

But now, even arrogant people like us are not simply right-clicking the mouse and looking at it.Source codeAnd then you can be sure of what is happening. Consider the following onreadystatechange JavaScript statement to respond to an XMLHttpRequest:

Xmlreq. onreadystatechange =
{
If (xmlreq. readystate = 4)
{
Eval (xmlreq. responsetext );
}
}

The above code is executed in the JavaScript code contained in the response from XMLHttpRequest. In other words, this may happen: even if a page is loaded, it is possible to add or modify JavaScript Functions and code in the background! Therefore, even if you observe the source code of the page code-it may have sent a key-click or mouse-move event to the Web server, you cannot be sure that the code you see is the only code currently executed. By combining these features with some daunting confusions, you can see that the combination of malicious purposes and XMLHttpRequest objects cannot steal information from Web customers!

4. Are you not sure?

Are you not afraid and angry? Are you still not ready to get angry and delete the XMLHttpRequest code in your browser? Well, maybe the strong wording in this article will scare you; then in the game "Fonzie treasure" (the search for's treasure. Note: If you enter these keywords in Google, you will surely find this online text game. I have not thoroughly tried it. Is this little thing so cute as to ambush the horrible one described above ......) -Can you rescue Fonzie?

Find the lost Arthur 'fonzie' Fonzarelli treasure through the text-filled foyer using the well-art command line interface. Good luck, but remember... Although it looks like a harmless customer interaction-every four moves you make, the game sends a request to the server through the XMLHTTPRequest object and saves your moves. Always remember: do not make a typo; Do not try stupid things such as "Eat jukebox"; do not enter a username and password in the game; otherwise ......

XMLHttpRequest

/*
* Author jouy. Lu
*/
VaR XMLHTTP; // first define a fully-local variable to save the object reference;
Function createxmlhttprequest () {// This method is used to create an instance of the XMLHTTPRequest object.
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
} Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
}

Considering compatibility with browsers, the recommended method is as follows:

VaR XMLHTTP;
Function createxmlhttp (){
If (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
If (XMLHTTP. overridemimetype ){
XMLHTTP. overridemimetype ("text/XML ");
}

}
Else if (window. activexobject ){
Try {
XMLHTTP = new activexobject ("msxml2.xmlhttp ");
} Catch (e ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
}
If (! XMLHTTP ){
Window. Alert ("Your broswer not support XMLHttpRequest! ");
}
Return XMLHTTP;
}
/*********************************** XMLHttpRequest Standard operation *********************
Abort (): Terminate the current request;
GetAllResponseHeaders (): return the HTTP Response Header as a key/value pair;
GetResponseHeader ("Header"); returns the string value of the specified header;
Open ("post/get/put", "url"); creates a call to the server. The URL parameter can be relative or absolute URL, this method also contains three other optional parameters;
Send (content); send a request to the server;
SetRequestHeader ("Header", "value"); set the specified header to the provided value. You must call open () before setting any header ().
Note:
Void open (string method, string URL, Boolean asynch, string username, string password): This method creates a call to the server.
You must provide the specific method (get, post, or put) to be called and the URL of the called resource. In addition, a Boolean value can be passed to indicate whether the call is asynchronous or synchronous,
The default value is true, indicating that the request is asynchronous in nature. If this parameter is set to false, the processing will wait until the slave server returns a response. Because asynchronous calls use Ajax
So if this parameter is set to false, it is not consistent with the original intention of using the XMLHTTPRequest object to some extent. In some cases, this parameter
Setting it to false is also useful. For example, you may want to verify user input before the persistent storage page. The last two parameters are self-explanatory and allow you to specify a specific user name and password.
Void send (content): This method sends a request to the server. If the request is declared asynchronous, this method will return immediately, otherwise it will wait until the response is received.
So far. The parameter is optional. It can be an instance of a DOM object, an input stream, or a string. The content of this object will be sent as part of the Request body.
Void setRequestHeader (string header, string value): This method sets the value of a given header in an HTTP request. It has two parameters, the first string table.
Indicates the header to be set. The second string indicates the value to be placed in the header. It must be noted that this method can be called only after open. Of all these methods
Is open () and send (). The XMLHTTPRequest object also has many attributes that are useful when designing Ajax interactions.
Void abort (): As the name suggests, this method is to stop the request.
String getAllResponseHeaders (): the core function of this method should be familiar to Web application developers. It will return a string containing all the sounds of the HTTP request.
Header. The header includes Content-Length, date, and Uri.
String getResponseHeader (string header): This method corresponds to getAllResponseHeaders (), but it has a parameter to indicate which one you want
Header value, and this value is returned as a string.


******************************/
/****************************** Standard XMLHttpRequest attribute ***** *****************
Onreadystatechange: This event processor is triggered for every state change. A JavaScript function is usually called.
Readystate: The Request status. Five values are available: 0 = not initialized, 1 = loading, 2 = loaded, 3 = interaction, 4 = complete.
Responsetext: server response, which is a string.
Responsexml: Server Response, expressed as XML. This object can be parsed into a DOM object.
Status: the HTTP status code of the server (200 corresponds to OK, 404 corresponds to not found (not found), and so on ).
Statustext: the text of the HTTP status code (OK or not found (not found ).
**************************************** ***********************************
*/

/********************** to see how to send a request *******
the basic steps for sending a request using the XMLHTTPRequest object are as follows:
1. you can obtain a reference to the XMLHTTPRequest object instance. Therefore, you can create a new instance or access a variable containing the
XMLHttpRequest instance.
2. Tell the XMLHTTPRequest object which function will handle the status change of the XMLHTTPRequest object. Therefore, set the
onreadystatechange attribute of the object to a pointer to a JavaScript function.
3. Specify the request attributes. The open () method of the XMLHTTPRequest object specifies the request to be sent. The open () method has three
parameters: one is a string indicating the method used (usually get or post), and the other is a string indicating the URL of the target resource, there is also a
Boolean value indicating whether the request is asynchronous.
4. Send the request to the server. The send () method of the XMLHTTPRequest object sends the request to the specified target resource.
the send () method accepts a parameter, which is usually a string or a DOM object. This parameter is transmitted as part of the Request body to the
Target URL. When providing parameters to the send () method, make sure that the method specified in open () is post. If no data is sent as part of the Request body
, null is used.

the asynchronous mode brings the user experience: (I want the programmer to see this explanation. It's really nice !)
requests sent to the server are sent asynchronously. Therefore, the browser can continue to respond to user input and wait for the server to respond in the background.
if you select synchronization, and the server response takes several seconds to arrive, the browser will be slow and cannot respond to user input during the
wait period. In this way, the browser seems to be frozen and cannot respond to user input. asynchronous
can avoid this situation, so that end users can have a better experience, although this improvement is very subtle, but it does make sense.
in this way, the user can continue to work and the server will process previous requests in the background. The
workflow that can communicate with the server without interrupting the user, so that many technologies can be used to improve the user experience. For example, assume there is an application that verifies user input. When the
user fills in fields in the input form, the browser can periodically send the form value to the server for verification, without interrupting the user.
, you can also enter the remaining form fields. If a verification rule fails, the user will be notified immediately, instead of
it will be known that an error exists only when the form is actually sent to the server for processing, which can greatly save the user's time, it can also reduce the load pressure on the server
server, because you do not have to completely recreate the form content when the form is not submitted successfully.

The following describes the security issues:
The XMLHTTPRequest object is subject to the browser's security "sandbox ". All resources requested by the XMLHTTPRequest object
Must be in the same domain as the calling script. This security restriction makes the XMLHTTPRequest object unavailable
Find resources outside the domain where the script is located. The intensity of this security restriction varies with the browser (see Figure 2-5 ). Internet Explorer
A warning is displayed, indicating that there may be a security risk, but the user can choose whether to continue sending the request. In Firefox
Stop the request and display an error message in the Javascript console. Firefox does provide some JavaScript skills,
So that XMLHttpRequest can also request resources of external URLs. However, these technologies are not recommended for specific browsers,
Avoid using XMLHttpRequest to access external URLs.
 
**************************************** ******************
*/

XMLHttpRequest member attributes

onreadystatechange * specifies the event handling handle when the readystate attribute changes. Write only
readystate return the status of the current request, read-only.
responsebody returns the response body in the form of an unsigned byte array. Read-Only
responsestream return the response information in the form of an ADO Stream object. Read-Only
responsetext return the response information as a string. Read-Only
responsexml Format the response information as an XML Document Object and return it, read-only
Status return the HTTP status code of the current request. Read-Only
statustext return the response line status of the current request, read-only

* Indicates that this attribute is an extension of the W3C Document Object Model.

Method

Abort Cancel current request
GetAllResponseHeaders Get all HTTP headers of the response
GetResponseHeader Obtain the specified HTTP header from the response information
Open Create a new HTTP request and specify the request method, URL, and authentication information (User Name/password)
Send Send a request to the HTTP server and receive a response
SetRequestHeader Specify an HTTP header of the Request separately
Related Article

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.