A detailed explanation of AJAX applications in JavaScript

Source: Internet
Author: User
Tags hash html header http post object model script tag sql injection

1: Definition
Ajax is all called "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML) and is a web development technology that creates interactive Web applications.
Ajax is not a single technology. In fact, there are several technologies, each with its own characteristics, and these technologies are merged in a new and powerful way. Ajax contains:

standards-based rendering using XHTML and CSS
Dynamic display and interaction using the Document Object model
Data exchange and operations using XML and XSLT
Asynchronous data retrieval using XMLHttpRequest
The JavaScript that binds them together
Although this technical description is somewhat outdated in some way, the basic pattern is still complete: HTML and CSS rendering data and styles, DOM and related methods support page real-time updates, XHR support and server communication, JavaScript arrangement overall display.

2. Principle
the principle of Ajax is simply to send an asynchronous request to the server via the XMLHttpRequest object, get the data from the server, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server.

In the past, we browsed the Web page by the client to submit the page request to the server, and then by the server will request through HTTP back to the client generated browsing page:

Working with Ajax, the following diagram shows a great improvement in user interaction through Ajax, which allows users to wait for a server to answer without having to submit a form for a long time, and can also develop gorgeous web interaction pages through Ajax.

To understand this process and principle, we must have an understanding of XMLHttpRequest.

3:xmlhttprequest
XMLHttpRequest is the core mechanism of Ajax, which is introduced first in IE5 and is a technology that supports asynchronous requests. Simply put, JavaScript is the time to request and process responses to the server without blocking the user. No refreshing effect is achieved. So let's start with XMLHttpRequest and see how it works. Www.111cn.net

First, let's look at the properties of the XMLHttpRequest object.

Its properties are:


Attribute description

onReadyStateChange the event handler for the event that triggers each state change.

ResponseText A string form that returns data from a server process.

Responsexml a DOM-compliant document data object returned from a server process.

Status number code returned from the server, such as common 404 (not Found) and 200 (ready)

Status Text string information accompanying the status code

ReadyState Object State Value

Object state Value:

ReadyState meaning

The 0 (uninitialized) object was established, but has not been initialized (the open method has not been invoked);

1 (initialization) object has been established and the Send method has not been invoked;

2 (send data) The Send method has been invoked, but the current state and HTTP headers are unknown;

3 (in the data transfer) has received part of the data, because the response and HTTP headers are incomplete, then through Responsebody and responsetext to get some of the data error;

4 (completed) data received, at this time through Responsexml and responsetext to obtain complete response data;

However, because of the differences between browsers, creating a XMLHttpRequest object may require different methods. This difference is mainly reflected in IE and other browsers. The following is a relatively standard method for creating XMLHttpRequest objects.

The code is as follows Copy Code
Function createxmlhttp ()
{
//non-IE browser creates the XMLHttpRequest object
if window. XMLHttpRequest)
{
xmlhttp=new xmlhttprequest ();
} The
//ie Browser creates a XMLHttpRequest object
if window. ActiveXObject)
{
Try
{
xmlhttp=new activexobject ("Microsoft.XMLHTTP");
}
catch (E)
{
try{
xmlhttp=new activexobject ("MSXML2. XMLHTTP ");
}
catch (ex) {}
}
}
}
Function Ustbwuyi ()
{
var Data=document.getelementbyid ("username"). Value
Createxmlhttp ();
if (!xmlhttp)
{
Alert ("Create XMLHTTP object exception!) ”);
return false;
}
Xmlhttp.open ("POST", Url,false),
Xmlhttp.onreadystatechange=function ()
{
if ( xmlhttp.readystate==4)
{
document.getElementById ("User1″)". Innerhtml= "Data is loading ...";
if (xmlhttp.status==200
{
document.write (xmlhttp.responsetext);
}
}
}
Xmlhttp.send ();
}

As shown above, the function first checks the overall state of the xmlhttprequest and guarantees that it is complete (readystatus=4), that is, the data has been sent. Then ask for the status of the request based on the server's settings, and if everything is ready (status=200), do what you need to do below.

For the two methods of XMLHttpRequest, open and send, where the Open method specifies:

The type of data submitted to the server, that is, post or get.
The URL address of the request and the parameters passed.
Transmission mode, false to synchronous, true to asynchronous. The default is true. In the case of asynchronous communication (true), the client does not wait for a response from the server; if it is synchronous (false), the client waits until the server returns the message before performing another operation. We need to specify the synchronization according to the actual needs, in some pages, may issue multiple requests, even organized and planned to have a large scale of the high intensity request, the latter will cover the previous one, this time of course to specify the synchronization mode.
The Send method is used for sending requests.

Knowing the XMLHttpRequest workflow, we can see that XMLHttpRequest is completely used to send a request to the server, and its role is limited to this, but its role is the key to the entire AJAX implementation, because Ajax is nothing more than two processes, Make a request and respond to a request. And it's completely a client-side technology. And XMLHttpRequest is to handle the server-side and client communication issues so it is so important.

Now, we can probably get an idea of the fundamentals of Ajax. We can think of the server side as a data interface, it returns a plain text stream, of course, this text stream can be an XML format, can be HTML, can be JavaScript code, can be just a string. At this time, XMLHttpRequest to the server to request this page, the server side will write the results of the text to the page, which is the same as the normal web development process, the difference is that the client after the result is asynchronous, not directly displayed in the page, but first by JavaScript to deal with, And then display it on the page. As for the many Ajax controls that are popular today, such as Magicajax, you can return other data types such as datasets, just encapsulate the results of the process, and they don't make much difference in nature.

4: Advantages and disadvantages
the advantages of Ajax
The advantages that Ajax brings to us are basically deeply appreciated, and here I just briefly say a few things:

The biggest point is the page does not refresh, in the page with the server communication, to the user experience is very good.
Communicate with the server in an asynchronous manner, without interrupting the user's actions and having a faster response capability.
Some of the previous server load can be transferred to the client, the use of idle client capacity to deal with, reduce the burden of server and bandwidth, save space and broadband rental costs. and reduce the burden on the server, the principle of Ajax is "on-demand data", can minimize redundant requests, and respond to the burden on the server.
Based on standardized and widely supported technologies, there is no need to download plug-ins or small programs.
Disadvantages of Ajax
Here's what I'll focus on about Ajax flaws, because most of our attention is about the benefits that Ajax brings to us, such as the improvement of the user experience. And the drawbacks of Ajax are overlooked.

The Ajax flaws described below are inherent in this.

1.ajax killed the Back button.

Ajax kills the Back button, which is a breach of the browser's fallback mechanism. The Back button is an important feature of a standard web site, but it does not work well with JS. This is a more serious problem with Ajax, because users often want to be able to undo the previous operation by backing back. So is there a way to do that? The answer is yes, Gmail to know that the following Ajax technology to solve this problem, under Gmail can be backward, but it does not change the AJAX mechanism, it is only a more stupid but effective way, that is, when the user clicks the Back button to access the history To reproduce changes on the page by creating or using a hidden iframe. (for example, when a user clicks back in Google Maps, it searches in a hidden iframe and then reflects the search results onto AJAX elements to restore the application state to its current state.) However, while this problem can be solved, the cost of development is very high, contrary to the rapid development required by the AJAX framework. This is a very serious problem brought by Ajax.

2 Security issues

Technology also poses a new security threat to IT companies, and Ajax technology is like establishing a direct channel for enterprise data. This allows developers to inadvertently expose more data and server logic than before. Ajax logic can hide the security scanning technology of the client, allowing the hacker to create new attacks from the remote server. Ajax also makes it difficult to avoid some known security vulnerabilities, such as cross-site attacks, SQL injection attacks, and credentials vulnerabilities.

3. Search engine support is relatively weak

4. The exception mechanism that destroyed the program

At least for now, these Ajax frameworks, like Ajax.dll,ajaxpro.dll, can disrupt the program's exception mechanism. On this issue, I have encountered in the development process, but looked up the Internet almost no relevant introduction. Then I did a test myself, using Ajax and the traditional form submission model to delete a piece of data ... To our debugging has brought a lot of difficulties.

5. Some other aspects of the problem

In addition, some problems like other aspects, such as violating the original intention of URL and resource positioning. For example, I give you a URL address, if you use Ajax technology, perhaps you see below the URL address and I see under this URL address is different. This is a departure from the original purpose of resource orientation.

6. Some handheld devices (such as cell phones, PDAs, etc.) are not yet well supported by Ajax

Some handheld devices (such as cell phones, PDAs, etc.) do not support Ajax very well now, for example, when we open an AJAX-enabled Web site on a mobile browser, it is not currently supported, of course, and it doesn't matter much to us.

5. Get and Post
When we do not reload the page and use AJAX to access the server, there are two choices to transfer the request information to the server. These two choices are get and post.

Get and post have a lot of things to write, I am here to specifically say the two applications in Ajax, the specific next time to write it ...

The purpose of get is to obtain information just like its name. It is designed to show the information you want to read on the page. The browser buffers The execution result of the GET request, and if the same GET request is issued again, the browser displays the buffered result instead of running the entire request again. This process differs from that of the browser, but it is intentionally designed to make get calls more efficient. The get call retrieves the data to be displayed on the page, the data is not changed on the server, and the same results are obtained when the same data is requested again.

The Post method should be used where you need to update the server information. If a call is to change the data saved on the server, the result returned from the two same post calls might be completely different because the value of the second post call is not the same as the first, because the first call has updated some of the values. Post calls typically get a response from the server rather than a buffer from the previous response.

The difference between get and Post
in Ajax we often use get and post requests. So when do I ask for a request, and when do I post it? Before making an answer, we first need to understand the difference between get and post.

Get is to add the parameter data queue to the URL that refers to the action attribute of the submission form, and the value corresponds to each field one by one in the form, as you can see in the URL. Post is the HTTP post mechanism that places the fields in the form and their contents in the HTML header to the URL address that the action attribute refers to. This process is not visible to the user.
For Get mode, the server end uses Request.QueryString to obtain the value of the variable, and for the Post method, the server end uses Request.Form to obtain the submitted data. The parameters of both methods can be obtained by request.
The amount of data transferred by get is small and cannot be greater than 2KB. Post transfers have a large amount of data, which is generally default to unrestricted. In theory, however, it varies depending on the server.
Get security is very low, post security is high.
<form method= "Get" action= "A.asp?b=b" > with <form method= "get" action= "a.asp" > is the same, that is to say, The list of arguments behind the action page when method is get is ignored, while <form method= "post" action= "A.asp?b=b" > and <form method= "Post action=" A.asp "> is not the same.
The other GET request has the following characteristics: It adds the data to the URL, which is passed to the server in this way, usually using a question mark? Represents the end of a URL address and the beginning of a data parameter, with each data parameter in the form of a "name = value", which is differentiated between parameters and parameters using a connector &. Post requests have the following characteristics: The data is placed in the HTTP body, the organization of more than one, there are & connection, but also have the way of dividing, can hide parameters, transfer a large number of data, more convenient.

Through the above instructions, now we have a general understanding of when to use get when the post way, yes! When we submit the form we usually use post, when we want to send a large data file, we need to use post. When the value passed is only in parameter mode (this value is not more than 2KB), you can use Get method.

6. Cross-domain
Ajax itself actually interacts with the data through the XMLHttpRequest object, and the browser, for security reasons, does not allow the JS code to operate across domains, so many Cross-domain solutions are born. When accessing between this domain and subdomain, it is easiest to set up document.domain, when access to different domains, there are probably the following methods:

1.web Proxy Way, that is, when a user visits a Web site, the cross domain access requests for B sites are submitted to a designated page of site A, which is used instead of the user page to complete the interaction, thus returning the appropriate results.

2.iframe, The solution is to use the hash property of the Window.location object, use JS to change the hash value of the page will not refresh, you can achieve through JS access to the hash value to do communication, is roughly AB site each embedded in a site of the IFRAME, and then through the continuous monitoring of the changes in the hash value to pass Letter. For example, a site by changing the hash of B site IFrame, b Web site after hearing the changes in the hash to deal with, this way requires developers can control the two Web site code.

3. Request by script tag, the principle is in the domain within a to generate a JS tag, its SRC point to the request of the other domain of a page B, this src will usually add a page defined a good callback function, b return data can be directly returned to call this callback function, This cross-domain communication is called JSONP, and the flaw in this scenario is that the script's SRC attribute completes the call when it takes the form of get, and may not function correctly if the string passed at the request is too large.

4. Window.name,window.name is a new technology to solve cross-domain data transmission, by loading a cross-domain HTML file in the IFRAME and setting the Window.name value in the HTML file as the data that needs to be passed to the recipient, the receiver can obtain the Window.name Value and returns, it is more critical that the impact of the homology policy is unrestricted for location control, so a page of the agent needs to be loaded to allow the sending page to read window.name.

5. Using Flash, the principle is that JavaScript will submit data to the local flash, through flash to access the interface of other domains, only the root directory of other domains have a crossdomain.xml file, the file settings allow all domain names or allow access to the domain.

Examples of specific cases I'll open another article in detail about cross-domain issues.

7. Security
Because Ajax is used to develop many applications that can be seen on the WEB, its popularity makes it a target for attackers to look for vulnerabilities in JavaScript code.

The core of Ajax existence is that it can be used to create data-driven Web sites. The real attraction for attackers is not that Ajax can be used as a WEB application development tool, but that data, whether financial, personal or confidential, is a valuable online commodity, and Ajax once again finds itself the focus of cyber crime.

A:
Browser-based attacks
JavaScript is the foundation of Ajax, and malicious code often uses it. For a browser-based attack to take effect, malicious code must be able to take advantage of WEB technology (this is JavaScript), allowing the browser to run its own code that the attacker wants to run. Www.111cn.net

As a simple example, in the event of a browser-based attack, the victim will find that the home page has been tampered with, or that the victim will be redirected to another Web site when he or she enters a URL in its browser's address bar. Although this is annoying and troublesome, these are not the worst cases.

Many browser-based attacks are designed to prevent infected computers from sending notifications or reducing other attacks. Typically, attacks on the victim's browser prevent them from accessing the malware cleaner or using a Web subscription file update. Other threats include browser proxy and keystroke logging.

Preventive measures
It's easier to protect yourself from browser-based attacks simply by disabling Java™ technology, JavaScript, and microsoft®activex® controls. However, doing so usually prevents many WEB applications from running. Instead, you should ensure that the operating system, browser software, and anti-virus software are updated in a timely manner. In addition, you can use a reputable firewall program and be cautious when downloading files and accessing Web sites.

B:
SQL Injection
How does SQL injection become a threat to Ajax security? After all, there is no "S" in Ajax. Very simply, SQL injection poses a threat because Ajax is running on the client. The SQL database is still required on the WEB application server side.

SQL injection occurs when an attacker enters malicious code into an imperfect area of the site, such as a form. If the compromised site is vulnerable, all of the contents of the database may be exposed. Password database exposure or stealing credit card data from the online payment system is the attack method. Recently, intruders have used this method to steal fan e-mail addresses from star sites. Despite the absence of theft, spammers use these email addresses to spread malicious software in the guise of star products.

As with other WEB technologies, you should mitigate SQL injection in applications that are developed using Ajax. However, using JavaScript-only sanitation technology is not enough to prevent this kind of exploitation. JavaScript is run on the client rather than on the server side, which is the main reason for SQL injection.

Preventive measures
When using Ajax, to protect your database, you must validate user input and the validation is done on the server side. parameterized statements, or preprocessing statements, are intended to prevent SQL injection because a value cannot be entered directly into a database or SQL statement. In contrast, when using placeholders (also known as binding variables), the value of a placeholder is provided through a separate API call.

C:
Cross-site Scripting
XSS is another example of an injection attack, and malicious code is injected into the application. Web applications that are susceptible to XSS attacks include browser-based scripting, just like those common Ajax attacks. Typically, attackers use such vulnerabilities to pass malicious scripts to visitors who are unsuspecting of the site. These scripts are responsible for identity theft, stealing cookies, spying on visitors ' Web usage, accessing confidential information, and even blocking service attacks.

The famous XSS attack, which became the focus of news in the 2010, involved social information networks. The attack started with a user named @Matsta, causing the JavaScript pop-up window to appear when the viewer's mouse slides over a malicious message. Other XSS attacks on the site cause users to be redirected to a Web site or content that is unhealthy.

Preventive measures
When using Ajax for development, you can use the following steps to prevent XSS vulnerabilities

Make sure that JavaScript variables are referenced.
Use JavaScript hexadecimal encoding.
Use JavaScript Unicode encoding.
Avoid backslash encoding (", ' or \).
Use Json.parse or json2.js libraries to parse JSON.
Avoid parsing JSON using the eval () method, which executes any script that contains JSON.
D:

Ajax Bridging
Ajax applications are built to connect to the Web sites hosting them. As a security measure, applications from site A cannot connect to site B. However, many sites rely on Third-party Web sites and data sources to create mashup sites. An Ajax bridging service is created that provides a WEB service through a host that acts as a proxy for forwarding data between JavaScript and Third-party sites running on that browser. Using the Ajax bridging, site A can now provide data or content to visitors from site B.

Just as Ajax is not a specific technology but a technology set, bridging is not a specific vulnerability. The Ajax Bridge provides an additional attack path for malicious hackers, adding to the threat. Attacks such as XSS and SQL injection can be delivered via an Ajax bridging service. Although site B may be doing everything possible to protect its Web applications from the corresponding threats posed by visitors, site A can use Ajax bridges to attack site B, which is often overlooked.

Preventive measures
To avoid bridging vulnerabilities, you need to establish trust between sites with third parties when using bridge access. You should also review how a Third-party site accesses your site and scan for any vulnerabilities that might be exploited by the bridge.

OK, the above is basically I think Ajax related technology and some things, the content is not complete, each point is worth our in-depth study.

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.