Learn AJAX

AJAX introduce the technical background
Ajax (Asynchronous JavaScript + XML) is not a technology. In fact, it consisted of several technologies to flourish with a new combination of a powerful way. Ajax include:
1. Based on the CSS standard express;
2. The use of Document Object Model (DOM object) for dynamic display and interaction;
3. The use of XMLHttpRequest asynchronous communication with the server;
4. The use of JavaScript to bind everything.
Ajax is the core JavaScript object XmlHttpRequest. The object in Internet Explorer 5 was first introduced, it is a request to support the asynchronous technology. In short, XmlHttpRequest lets you use JavaScript to the server request and response to treatment, rather than blocking the user.
Traditional Web application model and application of Ajax technology interface:

Traditional synchronous Web application interaction process and the application of asynchronous Ajax interaction comparison

XMLHttpRequest outlined in the use of XMLHttpRequest object to send requests and to respond to treatment before using JavaScript to create a XMLHttpRequest object. Because XMLHttpRequest is not a W3C standard, so can be used many ways to use JavaScript to create XMLHttpRequest instances. Internet Explorer put an ActiveX implementation XMLHttpRequest object, other browsers (such as Firefox, Safari and Opera) put it to achieve a local JavaScript object. Because of these differences exist, JavaScript code must contain the relevant logic, and thus the use of ActiveX technology or the use of local JavaScript object technology to create an instance of XMLHttpRequest.
A lot of people may still remember the days before, when different browsers on the JavaScript and the DOM implementation is different, having listened to these words above, these people may have a chilling effect. Fortunately, here in order to clear the how to create XMLHttpRequest object instance, then the detail is not necessary to write code to differentiate the type of browser. You need to do is check the browser whether or not to provide support for the ActiveX object. If the browser supports ActiveX objects, you can use ActiveX to create XMLHttpRequest object. Otherwise, it is necessary to use local technology to create a JavaScript object. The following code demonstrates the preparation of cross-browser JavaScript code to create XMLHttpRequest object instance is very easy.

Create an instance of XMLHttpRequest object
var xmlHttp;

function createXMLHttpRequest () (
if (window.ActiveXObject) (
xmlHttp = new ActiveXObject ( "Microsoft.XMLHTTP");
)
else if (window.XMLHttpRequest) (
xmlHttp = new XMLHttpRequest ();
)
)

Can see, relatively easy to create XMLHttpRequest object. First of all, we create a global scope variable to save the xmlhttp object. createXMLHttpRequest Ways to create XMLHttpRequest instances to complete the specific job. This method is easy, only a branch of logic (selection logic) to determine how to create objects. Of the call will return window.ActiveXObject an object may also return null, if statements will be called back as a result of true or false (if the target return was true, return null for false), as instructed browser whether or not to support ActiveX controls, corresponding to learn that the browser is not Internet Explorer. If there are, then through the instantiation of a new instance of ActiveXObject to create XMLHttpRequest object, and the introduction of a string of instructions to create the type of ActiveX object. In this example, provided for the constructor string are Microsoft.XMLHTTP, This shows that you want to create an instance of XMLHttpRequest.

If window.ActiveXObject calls fail (return null), JavaScript will go else branch statement to determine whether the browser XMLHttpRequest implementation for a local JavaScript object. If there are window.

XMLHttpRequest, will create an instance of XMLHttpRequest.

Because of dynamic types of JavaScript features, but at different XMLHttpRequest browser implementation are compatible, so could use the same access to XMLHttpRequest instance properties and methods, regardless of the method to create this example is. This greatly simplifies the development process, but also in JavaScript there is no need to prepare in the browser-specific logic.

Ajax Core: XMLHTTP component database related technologies remote management technology is based on the Internet WAN modern applications are an important aspect RMON database. First of all, easy to recall the Internet database on the remote management technology development process and the way:
1, early through the preparation of CGI-BIN program modules to carry out remote management database. But the CGI-BIN running slow, maintenance is very convenient, and now has basically been dropped.
2, over the past few years the use of Component Object Model (Component Object Model, COM) applications is very large, was also very effective. However, if you are using a third-party server, the server side is often because of commercial confidentiality or other reasons do not allow users to register their own components.
3, in recent years, launched by Microsoft. NET platform and SUN's J2EE platform, the database is very high-grade remote management and service platform. Can provide high-quality multi-layer (n-Tier) application services. One of,. NET's Simple Object Access Protocol (Simple Object Access Protocol, SOAP) using the Hypertext Transfer Protocol (Hypertext Transfer Protocol, HTTP) and Extensible Markup Language (Extensible Markup Language, XML) technology to achieve cross-system (such as Windows - Linux) communications services has been widely accepted and used developer. Lot of large-scale applications such as enterprise resource planning (Enterprise resource planning, ERP) have set up in such a large platform. But for small and medium-sized applications, such as a website building and maintenance of such large-scale application platform has become some popular practice, spending is also too large.
Once on the Internet technology and Java technology was behind the Microsoft Corporation in the XML application development is going at the front. Her XML Parser (MSXML) of XMLHTTP protocol is a very convenient and practical of the client / service communication channels. Comprehensive use of XMLHTTP and ActiveX Data Objects (ActiveX Data Objects, ADO / ADOX) can easily achieve easy remote management database.
Remote database management system database remote management of the mission flow are:
1, client-side Service issued to the database structure and data query or modify the instructions.
2, Service client to accept and carry out the relevant instructions to return the results of the client.
3, the client side to accept and display the Service return the results of instruction execution.
Implementation of two remote management database key aspect are:
1, the client and services between the client's instructions to upload and download the results of the data path, from XMLHTTP protocol implementation.
2, services and database front-end between the command transfer and the results back by the middle layer plays the role of ADO / ADOX interface completed.
XMLHTTP use as the name implies, XMLHTTP is an XML format for data transmission Hypertext Transfer Protocol. In fact, XMLHTTP data transmission process is more flexible, it can upload instructions are XML-format data may also be a string, stream, or an unsigned integer array. Also can be a URL parameter. It issued the results are XML-format data may also be a string, stream, or an unsigned integer array.
XMLHTTP client calls the process is very simple, only five steps:
1, create XMLHTTP object
2, open-end connectivity and services, while the definition of commands to send the way Service web page (URL) and request such permission.
Client through the Open command to open and service-side Service web page link. With ordinary HTTP to send the same command can be used to "GET" method or "POST" method point to the Services page Services client.
3, send commands.
4, Wait for and receive services deal with the back-end results.
5, release 1 XMLHTTP object, XMLHTTP Ways
Open (bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword)
bstrMethod: data transmission, that is, GET or POST.
bstrUrl: Service web page URL.
varAsync: whether the synchronous implementation. Default to True, that is, synchronous implementation, but only at the implementation of DOM to implement synchronization. Applications will generally be its home for the False, that is, asynchronous implementation.
bstrUser: user name, can be omitted.
bstrPassword: user password can be omitted.
Send (varBody)
varBody: instruction set. XML format can be data, can also be a string, stream, or an unsigned integer array. Can also be omitted (null), so that methods of instruction through Open parameters into the URL.
setRequestHeader (bstrHeader, bstrValue)
bstrHeader: HTTP header (header)
bstrValue: HTTP header (header) value is defined as if the Open method POST, the form can be defined the way From xmlhttp.setRequestHeader "Content-Type", "application / x-www-form-urlencoded"
Second, XMLHTTP property
onreadystatechange: At synchronous implementation of the outcome of the way back under the handle of the case. Can only call at DOM.
responseBody: the results back as an array of unsigned integers.
responseStream: the results back to IStream stream.
responseText: results for the string back.
responseXML: the results back as XML formatted data.

Three, HTTP ready state of the above-mentioned, the server after the completion of the request at the onreadystatechange property of XMLHttpRequest to call the search method. This is true, but not yet complete. In fact, whenever the HTTP ready state changes it will call the method. Must first understand the HTTP ready state. HTTP ready express request of the state of the state or situation. It is used to determine whether the request has already begun, whether it be a response or request / response model has been completed. It can also help determine the servers to respond to read the text or data is safe. At Ajax applications need to be aware of the five-ready status:
• 0: request was not sent (at call open () before).
• 1: the request has been issued but has not set up (call the send () before).
• 2: the request has been issued are now being processed (in this case can usually be obtained from the response to the contents of the head).
• 3: request have been processed, the response usually has part of the data available, but the server response is not yet complete.
• 4: Response has been completed, you can access the server response and use it.
Demo Code:
function updatePage () (
if (request.readyState == 4)
alert ( "Server is done!");
)

Four, HTTP status code

Therefore, in addition to a state of readiness, but also need to check the HTTP status. We look forward to the status code is 200, which express all the best. If the ready state is 4 and status codes are 200, you can deal with server data, and these data should be the requested data (rather than an error or other information there is the question). Therefore also an increase in the callback method to check the status of

Demo Code:
function updatePage () (
if (request.readyState == 4)
if (request.status == 200)
alert ( "Server is done!");
else if (request.status == 404)
alert ( "Request URL does not exist");
else
alert ( "Error: status code is" + request.status);
)
AJAX problem of more than half of the AJAX security risks implicit in the server from the loophole. Clearly, the use of security coding techniques of good design, safer for AJAX great help, we need to thank the Max familiar with the Open Web Application Security Plan (the Open Web Application Security Project - OWASP) top ten most serious web application security loopholes in the list. Unfortunately, when Max's AJAX implementation, he still faces a number of extra factors:
1. The new technology: If you want the site to connect to a SQL database, available at Google millions of examples. AJAX technology, no matter how young this technology, it still appears in the procurement cycle are in relatively early, although only a small part of it appears in the best example of the network. In order to solve some intractable problem and unnecessary complexity, which requires developers to self-development. Have to prepare the server side and client-side code to create himself not sure of the protocol (especially in terms of server response). No matter how good these agreements are to be manifested in a timely manner on the page.
2. Non-traditional forms of design: AJAX has a little bit different from the traditional design, because such applications are semi-semi-Service client-side. So developers for the server and client are able to encode. At the same time using two different languages (especially at the early stages) to development will have some initial coding errors, because developers have to jump back and forth at both ends of one end of a very good run, but at the other end may not be able to do. Even if the developer has a large development team, security duty may also be encoded in the service client and the client code transfer between development team when a problem occurs.
3. Too many scripting languages: developers by virtue of his own wisdom decided to set up the best in the world travel registration instrument. You enter your current location (via zip code, phone area code, or GPS, etc.) to begin the registration, this time an AJAX request will be sent immediately to determine your exact location. Since then, the screen will fill up all your available to travel the way, all this even in your decision what you want to go places, do you intend to go and when and who you intend to go together before the completed .
On the screen and control cells are filled with AJAX-driven, server-side and client-side scripting may be needed more than 20 different server call. You can imagine a very small individual server program, such as findairportsbylocation.aspx or determinemaxbaggageallowancebyairline.php.
Obviously, if there is no developer carefully plans (such as the creation of multi-purpose "overloaded" JavaScript function and server script), every time he would need to create the design of more than 40 separate parts. More programming means that will produce more errors and bug, implies the need for more time to prepare, manage, test and update the code. Not only that, because the client's JavaScript code in the application of a large number of such scripts, they are formal procedures to test also tend to become very forgetful.
4. To determine a small part of the AJAX will not cause harm: This site is a site plan to travel, but Max will be taken into account are immediately displayed for you to provide a precise location of the satellite view, and put you to the destination weather conditions Here you are also provided. The biggest temptation AJAX one looked as if he was in it until the last moment the other operation, like a guide to explain where, like the use of AJAX for AJAX. When Max began to try his new ideas, he will gradually try to add more new features, totally ignored the needs of the test.
5. Insecure communication: every AJAX call may only return a small number of data to the client, but those data are private and confidential. Developers can write a convenient instrument to your credit card number to the number of parity, but if you use plain text to replace over SSL to send data would happen then? This is an obvious problem, but when there is much need to be considered a routine procedure, especially the screen on the other 99% of the data is not really confidential data can easily be overlooked out of SSL.
6. Server-side access control: the use of JavaScript to trigger AJAX procedures often conceal some obvious coding error, server-side access control is an example. The assumption that developers want to reference your last visit, a detailed destination to provide you with your favorite hotels, he might like the following:
showprevioushotels.aspx? userid = 12345 & destination = UK
This, of course, are very good, but if a malicious user put into the URL shown below how to do it:
showprevioushotels.aspx? userid = 12346 & destination =%
They will get other people's favorite hotel吗? (Note:% in the SQL statement is a wildcard). There is no doubt that this is an example of Nothing against, but developers should use session, cookie or other symbolic forms to ensure that data can and can only be sent to the correct users. They may only a small portion of data, but they may be the most important one small part.
7. Server-side validation: in fact there are two questions here. First, AJAX are often used to control the user before final submission to the server input validation. This is because a server-side inspection, when this page was submitted by the last time he does not have to once again make up for the server checks to worry about, here we assume that there is a malicious user will not undermine alloweddestinations.php response from the server or damaging Finally request.
AJAX control can be more carefully than the user's own input to authenticate users, but they are often the last to do on the server first to verify.
AJAX validation The second issue is the control itself will be to verify the impact of vulnerabilities. Here again to emphasize, URL is usually hidden, so it will often forget. Example to illustrate this point, maybe I can use SQL Injection to just attack script, as follows:
showprevioushostels.aspx? userid = '; update users set type =' admin 'where userid = 12345; --
Will let me log in with system administrator after the permissions. Of course, how to get those table name (table) and field names have been beyond the scope of this article, but you already know this situation, is not it?
8. Client-side validation: We already know at just the Google Suggest example, client service through a simple evaluation of the response to the creation and implementation of post-dynamic JavaScript function is feasible. If there is no any form of authentication (If this is the case the client is very difficult to guarantee reliability and fluency), the client will be easy just need it to complete the implementation of the server thing.

AJAX Safety Tips 1, in order to be successful, you must be well planned. Must concentrate on your talents to reduce and simplify the AJAX call, create a standard response format, at any place should be guided by this Agreement (the ideal XML).
2, following from the World Wide Web applications, like opening up the site security plan as the optimal method. This special includes a visit inside the control and input validation vulnerability checks, while ensuring that the use of sensitive information over SSL is better than using plain text.
3, Forever not to assume that server-side AJAX for access control or user input checking on the server be able to replace the final re-inspection. AJAX Control will never be increased to reduce the workload of your authentication, they can only increase your workload.
4, always assume that the client not to confuse technology (obfuscation, here JavaScript ordered quite difficult to read and decode) can protect your very important commercial secrets. The use of JavaScript programming are hidden the most useless as a means also to be able to provide the benefits of your opponent.
5, finally, you must be very good leadership of your development team.