Ajax detail_dynamic node Java school arrangement, ajaxjava
In the past few years, JavaScript has changed from an accidental object that reminds people of events to the most important Web language. If you want to point out a factor that drives significant technological advances, it is the emergence of Ajax-based application development.
Develop technologies on this topic
In short, Ajax is a development technology that supports websites or applications and uses real-time data update interfaces without page refresh. This feature creates a smoother and more desktop-style user experience.
A Brief History of Ajax
The development history of Ajax is similar to that of many other overnight famous technologies. Although Ajax does not seem to come from, it has been in existence for a long time. After years of efforts, you can create tools and models under the guidance of Ajax. Looking at the DHTML era of the network bubble and the dark age after the bankruptcy of the network company, developers around the world have lifted the super power of JavaScript, introduce this brand new and exciting application model to the Web.
XMLHttpRequest
The first and most important Ajax puzzle was the XMLHttpRequest (XHR) API. XHR is a JavaScript API used to transmit data messages between a Web browser and a Web server. It supports http post (transfer data to the server) or GET requests (access data from the backend server) in the browser ). This API is the core of most Ajax interactions and a basic technology for modern Web development.
It is also Microsoft®Internet Explorer®The best gift the team has contributed to the Internet.
This is true. As early as 2000, XHR first appeared in IE 5. Microsoft was originally compiled by Alex mongomann®ActiveX®Control, XHR is created to process Microsoft Outlook®Web Access aims to solve the interaction between the advanced (then) Front-End Interface and Microsoft Exchange Server.
Although Microsoft's software package is not completely "born from poverty", the development of XHR is far beyond the scope of the original product. Later, it was implemented in various major browsers, it is even adopted as a W3C standard.
Pioneer
In addition to Microsoft, some other enterprises have begun to enter the prototype Ajax field. Many enterprises are trying to use these technologies, two of which are particularly worth mentioning-one is because it is an interesting and often cited Ajax development footer, the other reason is that it is the Internet giant that makes these technologies popular.
Oddpost
Oddpost is a Web-based advanced mail client launched in 2002. It leverages many well-known models. In terms of design and interaction, people will think of desktop mail clients. In the system, Oddpost transmits small pieces of data from the server to the browser using the concept of DataPacks. This will bring a new experience.
Oddpost is finally thrown by Yahoo! Acquired to become Yahoo! The foundation of the Mail revision.
Google Maps, Google Suggest, Gmail, and an important article
The real change started with the Gmail, Google Suggest, and Google Maps services a few years later. The use of these three Ajax technologies makes the Web development field boil. Its response capability and interactivity are brand new to the public. The new Google application soon caused a sensation.
Although not many people know about it, the Web development community has a very strong response. At that time, people knew that some new and exciting content had emerged in Web application development. However, for a long period of time, the "content" was vague.
What people need is an article that makes the content clear.
In February 18, 2005, Jesse James Garret, co-founder and president of Adaptive Path, wrote an article entitled "Ajax: A New Approach to Web Applications. In this article, he introduced the trend of Web application design and development, such as Gmail and Google Maps. He called this trend "a fundamental change in Web development may be triggered ."
He also named this pattern, which is an important moment, because from this moment on people began to focus on this new trend, everyone (or even non-professional) it will be mentioned when talking about the latest changes in the Web development field. In this article, he introduced Ajax technology as follows:
Define Ajax
Ajax is not a technology. There are actually several technologies, each of which has its own unique characteristics. These technologies are integrated in a new and powerful way. Ajax includes:
- Standard-Based Rendering using XHTML and CSS
- Use the dynamic display and interaction of the Document Object Model
- Data exchange and operations using XML and XSLT
- Use XMLHttpRequest for asynchronous data retrieval
- The JavaScript code that binds them together
Although this technology is somewhat outdated to some extent, the basic mode is still complete: HTML and CSS are used to present data and styles. DOM and related methods support real-time page updates, XHR supports communication with the server, and the overall display of JavaScript is arranged.
The overall impact of this article is relatively large. The intensive publicity and the collision of creative power and energy that need to be developed have set off a revolution, which is rare. Because Ajax has been adopted by a new generation of entrepreneurial enterprises around the world, it has quickly moved to the forefront of the Web development paradigm. Ajax jumped from a fuzzy trend seeking market strategies to a key part of modern Web design development.
Library
A key driver for Ajax-based development is the evolution and improvement of several full-featured JavaScript libraries. Few experienced JavaScript developers can really understand the underlying Ajax technology. Therefore, even in the DHTML era, although most browser interactions and animations have been developed to deal with the trivial excess, however, a limited number of experienced JavaScript engineers have led to further expansion of the gap between Ajax-based site demands and talent (they can write such an interface from scratch. By providing ready-to-use interaction and animation, we can reduce cross-browser differences and improve the implementation of core JavaScript API defects. Prototype, Dojo, and jQuery Libraries help fill this gap on a large scale.
Asynchronous JavaScript and more JavaScript (Object Notation)
From the original post era to the modern era, the biggest change in the Ajax field is the introduction of JSON, which is a JavaScript-based data transmission. Providing smaller files and more convenient native JavaScript access (contrary to the cumbersome DOM-based methods and attributes used by XML), JSON is quickly used by developers for data transmission. JSON is now included in version 5th of the recently completed ECMAScript specification.
JSON + Padding
A significant enhancement proposed by the original JSON is JSON + Padding (JSONP ). As you can see, the XMLHttpRequest object has a strict security model that only supports communication using the same domain name and protocol as the request page. JSONP creates a more flexible method for this cross-origin restriction and encapsulates the JSON response into a user-defined or system-provided callback function. After a JSON script is added to a document, this method provides real-time data access. This mode is now common. For many large Web Services, this practice can be used to support combination of mashups and other content.
Despite the popularity of JSONP, it has a major vulnerability that facilitates malicious code intrusion. Because script tag injection from a third party allows all content to run on the host page, when the data provider is threatened or the host page does not pay attention to page resource insertion, the potential of malicious intrusion will be unimaginable.
Now that you know some about Ajax history, we will start to explore technologies that turn magic into reality. Although common JavaScript API books are everywhere in the library, it is still enlightening for experienced developers to understand the underlying Working principles.
XMLHttpRequest API and features
Although other technologies can be used to return data from the server, XHR is still the core of most Ajax interactions. XHR interaction consists of two parts: request and response. Next we will introduce them one by one.
Security Model
As mentioned above, the original XMLHttpRequest object has a strict security model. This same-origin policy only allows communication between hosts, protocols, and ports that are the same as the request page. This means communication between different domains (example.com and example2.com), different hosts (my.example.com and www.example.com), and different protocols (http://example.com and https://example.com) is forbidden, which produces error messages.
With the development of the second XHR object, the new cross-origin request protocol will be completed in W3C, and a lot of implementation work will be done by the browser vendor, currently, cross-origin request targeting mechanisms are only available in Internet Explorer 8 +, Mozilla Firefox 3.5 +, Apple Safari 4 +, and Google Chrome. Although the development has slowed down, a specific "Origin" header is still sent in the request:
Origin: http://example.com
Configure the server to send back a matched "Access-Control-Allow-Origin" header:
Access-Control-Allow-Origin: :http://example.com
Now, you can use the XHR object for cross-origin bidirectional communication.
Request
The requester has four methods:
- Open () initiates a server connection. Parameters can be included:
- Method. The HTTP method to be used (can be POST or GET)
- Url. Request URL
- Async. Optional Boolean parameter, indicating whether the request is asynchronous (the default value of this parameter is true)
- User. An optional user name for authentication
- Password. An optional password for authentication
- SetRequestHeader () sets the request header with two parameters: header and its related values.
- Send () sends the request. This method has an optional parameter that contains the body of the POST request.
- Abort () abort request
Response
Response also has several attributes and methods:
- Status. Standard HTTP status of the request (for example, 200 is returned for a successful request)
- StatusText. Includes the complete response string returned by the Web server, including the response text (for example, 304 Not Modified)
- GetResponseHeader (). Returns the content of a specific header. The request header name is its unique parameter.
- GetAllResponseHeaders (). Returns the text of all response headers.
- ResponseText. String Representation of the response text
- ResponseXML. XML Representation of the response text, a document segment containing DOM and all relevant DOM Methods
ReadyState
After instantiation, the XMLHttpRequest object has five statuses, which are represented by the following values:
- 0: UNSENT. Indicates that the object has been created.
- 1: OPENED. Indicates that the open () method has been successfully called.
- 2: HEADERS_RECEIVED. Indicates that the request header has been received
- 3: LOADING. Indicates that the response header has been downloaded.
- 4: DONE. Indicates that the request is completed, but does not indicate whether the request is successful or the expected value is returned (query the response and standard HTTP header to estimate the request health status)
A common JavaScript example
Before we further introduce the popular library, we should first use several original JavaScript examples to understand the core technologies being used.
Sample HTML document
<!doctype html>
The following is an example of a simple GET request that processes responseXML. This is a typical Ajax interaction in the early development of this technology. It can run in all modern browsers as well as Internet Explorer 7 and 8.
A basic Ajax Function
/*Here's a basic Ajax function*/var ajax = function( opts ) {/*We have an options argument. In addition, we want to have some smart defaults.*/ opts = { //Is it a Get or Post type: opts.type || "POST", //What URL are we going to hit? url: opts.url || "", //What do we do with the data onSuccess: opts.onSuccess || function(){}, //what kind of data do we expect? data: opts.data || "xml" };//create a new XMLHttpRequest var xhr = new XMLHttpRequest();//Open the connection to the server xhr.open(opts.type, opts.url, true);/*When the ready state changesfire this function*/ xhr.onreadystatechange = function(){ //readyState 4 is "done" if ( xhr.readyState == 4 ) { /* do some simple data processing There are two components to the returned object- responseXML and responseText. Depending on what we're doing we'll need one or the other. */ switch (opts.data){ case "json": //json is text opts.onSuccess(xhr.responseText); break; case "xml": //XML retains the structure/DOM //It's passed in whole. opts.onSuccess(xhr.responseXML); break; default : //Everything else will get TXT opts.onSuccess(xhr.responseText);; } } }; //close the connection xhr.send(null);}//here's our simple functionvar ajaxSample = function(e){//Simple callback adds some text to the page var callback = function( data ) { document.getElementById("main").innerHTML += "<p>" +data.getElementsByTagName("data")[0].getAttribute("value") +"</p>";}//And here's our Ajax call ajax({ type: "GET", url: "_assets/data/ajax-1.xml", onSuccess: callback, data : "xml" })//prevent the default action e.preventDefault();}//Wire everything updocument.getElementById("activate").addEventListener("click", ajaxSample, false);
The following example shows the original ActiveX object of the activity. Without local implementation, you can use Try... Catch Block in different versions of Internet Explorer to traverse the potential references of objects cyclically. This complete cross-browser implementation is compatible with Internet Explorer, and even with the ancient Internet Explorer 5.
A cross-browser Ajax script
var ajax = function( opts ) { opts = { type: opts.type || "POST", url: opts.url || "", onSuccess: opts.onSuccess || function(){}, data: opts.data || "xml" };/*Support for the original ActiveX object in older versions of Internet ExplorerThis works all the way back to IE5.*/ if ( typeof XMLHttpRequest == "undefined" ) { XMLHttpRequest = function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} throw new Error("No XMLHttpRequest."); }; } var xhr = new XMLHttpRequest(); xhr.open(opts.type, opts.url, true); xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 ) { switch (opts.data){ case "json": opts.onSuccess(xhr.responseText); break; case "xml": opts.onSuccess(xhr.responseXML); break; default : opts.onSuccess(xhr.responseText);; } } }; xhr.send(null);}var ajaxSample = function(e){ var callback = function( data ) { document.getElementById("main").innerHTML += "<p>" +data.getElementsByTagName("data")[0].getAttribute("value") +"</p>"; } ajax({ type: "GET", url: "_assets/data/ajax-1.xml", onSuccess: callback, data: "xml" }) e.preventDefault();}document.getElementById("activate").addEventListener("click", ajaxSample, false);
The following shows a more common mode: Use responseText in JSON format and parse it into a local JavaScript Object. This Code demonstrates a simple JSON data processing method. Why do many developers choose to use JSON to transmit data and compare the list with the occasional indirect and lengthy method required to operate XML data? The answer is obvious.
Use JSON
var ajax = function( opts ) { opts = { type: opts.type || "POST", url: opts.url || "", onSuccess: opts.onSuccess || function(){}, data: opts.data || "xml" }; var xhr = new XMLHttpRequest(); xhr.open(opts.type, opts.url, true); xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 ) { switch (opt.sdata){ case "json": opt.onSuccess(xhr.responseText); break; case "xml": opt.onSuccess(xhr.responseXML); break; default : opt.onSuccess(xhr.responseText);; } } }; xhr.send(null);}var jsonSample = function(e){ var callback = function( data ) { //here, the data is actually a string //we use JSON.parse to turn it into an object data = JSON.parse(data); /* we can then use regular JavaScript object references to get at our data. */ document.getElementById("main").innerHTML += "<p>" + data.sample.txt +"</p>"; } ajax({ type: "GET", url: "_assets/data/json-1.json", onSuccess: callback, data : "json" }) e.preventDefault();}document.getElementById("activate").addEventListener("click", jsonSample, false);
JSON data is used in the following example.
A simple JSONP example is provided. As you can see, by using a callback parameter, you can avoid simply attaching XHR to the script. Return to the callback and wrap the data object in executable JavaScript code.
JSONP data
var callback = function( data ) { document.getElementById("main").innerHTML += "<p>"+ data.sample.txt +"</p>";}var jsonpSample = function(e){//create a script element var jsonp = document.createElement("script");//give it a source with the callback name appended in the query string jsonp.src= "_assets/data/jsonp.do?callback=callback";//add it to the doc document.body.appendChild(jsonp); e.preventDefault();}//wire up the eventdocument.getElementById("activate").addEventListener("click", jsonpSample, false);
Library example
For most developers, only those conducting academic research will be interested in the texture of Ajax requests. Most of the actual work is done in one or more JavaScript libraries. In addition to fixing cross-browser incompatibility, these libraries provide features built on the basic API. The following example shows the GET and POST examples in the three popular libraries to introduce different APIs.
JQuery
Let's start with the popular jQuery library. JQuery's Ajax functions have recently been rewritten to include several advanced functions. This is not the scope of this article, however, all common functions of jQuery Ajax requests exist in the form of parameters passed to the configuration object of the function. In addition, jQuery has several convenient methods, such as $. post and $. get, which are Shortcut Keys configured for common requests.
Shows the simple code for getting data using jQuery.
A jQuery GET request
/*callback is a simple function that will be runwhen the data is returned from the server*/var callback = function( data ) {/* it just adds a little bit of text to the documentdata is the JSON object returned by the server. */ $("#main").append($("<p />").text(data.sample.txt));}/*Wire up the ajax call to this click event*/$("#activate").click( function(){//call $.ajax with a configuration object $.ajax({//it's just a get request type: 'get',//we're looking for this URL url: '_assets/data/json-1.json',//Our cool callback function success: callback,//it's going to be JSON dataType: "json" }) } )
The following shows how to publish and retrieve simple JSON objects. Note that the native JSON object is used to analyze the input data. The jQuery document explicitly mentions the need to use JSON2.js scripts to add unsupported browsers.
An explicit error handle is provided to allow both successful and failed requests to be processed elegantly. JQuery's error status includes three parameters, including the XHR object itself, which supports robust error handling.
A jQuery POST
/*this is the object we're going to post*/var myMessages = { positive : "Today is a good day", negative : "Today stinks", meh : "meh"}var callback = function( data ) { $("#main").append($("<p />").text(data.positive));}/*Setting up a simple error handler.It doesn't do much. It's just nice to illustrate error handling.*/var errorHandler = function( xhr, textStatus, errorThrown ){ throw new Error("There was an error. The error status was " + textStatus );}/*Here's where the action happens.Attach an event to out simple button.*/$("#activate").click( function(){//call $.ajax with a configuration object $.ajax({ //we're sending data to the server type: 'POST', //this is our URL url: '_assets/data/post-responder.do', /* This is our data, JSON stringified jQuery expects to use native JSON or JSON2.js in unsupported browsers */ data: JSON.stringify(myMessages), //Here's where we set up our callback function success: callback, //The data expected from the server dataType: "json", //And our simple error handler error : errorHandler } ) });
Dojo
Dojo is not just a simple Ajax request/DOM operation demonstrated in the following example. It is actually built for hard core application development. This means that it is still worth looking forward to viewing the API in this way.
Note two independent "Ajax" functions: xhrGet and xhrPost. In addition, the Dojo JSON utility is used to analyze input data. The following shows a GET example.
One Dojo GET request
var callback = function( data ) {//note the document.getelementById alias dojo.byId("main").innerHTML += "<p>"+ data.sample.txt +"</p>";}var getData = function(){//xhrGet is for get requestsdojo.xhrGet({ //the URL of the request url: "_assets/data/json-1.json", //Handle the result as JSON data handleAs: "json", //The success handler load: callback});}// Use connect to attach eventsdojo.connect( dojo.byId("activate"), "onclick", getData );
The following shows a Dojo POST that contains the configuration of an error handle.
Dojo POST
var myMessages = { positive : "Today is a good day", negative : "Today stinks", meh : "meh"}var callback = function( data ) { dojo.byId("main").innerHTML += "<p>"+ data.positive +"</p>";}var errorHandler = function(){ throw new Error("We dun goofed.")}var postData = function(){ //not surprisingly xhrPost is for POST dojo.xhrPost({ // The URL of the request url: "_assets/data/post-responder.do", //This will be JSON handleAs: "json", //Set the headers properly headers: { "Content-Type": "application/json; charset=uft-8"}, //Use Dojo's JSON utility postData: dojo.toJson(myMessages), // The success handler load: callback, // The error handler error: errorHandler });}// Use connect to attach eventsdojo.connect( dojo.byId("activate"), "onclick", postData );
Yahoo! User Interface (YUI)
The YUI Library provides a slightly different mode from the previous two. First, YUI returns the entire XHR object, which not only parses data, but also allows more accurate operations on returned data and visibility of the entire request. This also means that developers need to understand the ins and outs of XHR objects. In addition, the usage of the YUI module loader use () is also shown here. It should be noted that, even if it is not directly related to Ajax (except loading the io module ). There is a list of YUI modules and a callback function used as a parameter. Once running! Content Delivery Network (CDN) download package, Yahoo! Content Delivery Network (CDN) contains all the modules required for a single CDN-based download package.
One yui get request
// Create a new YUI instance and populate it with the required modules.YUI().use('node','event', 'json', 'io', function (Y) { var callback = function( id, xhr ) { var data = Y.JSON.parse(xhr.responseText); Y.one('#main').append("<p>" + data.sample.txt +"</p>"); } Y.one("#activate").on('click', function(){ Y.io( '_assets/data/json-1.json', { //This is actually the default method: 'get', on: {success: callback} }) } )});
The following POST example shows an interesting style that further splits all response functions into on objects.
YUI POST
YUI().use('node','event', 'json', 'io', function (Y) { var myMessages = { positive : "Today is a good day", negative : "Today stinks", meh : "meh" } var callback = function( id, xhr ) { var data = Y.JSON.parse(xhr.responseText); Y.one('#main').append("<p>" + data.positive +"</p>"); } var errorHandler = function( id, xhr){ throw new Error("There was an error. The error status was " + xhr.statusText +".") } Y.one("#activate").on('click', function(){ Y.io( '_assets/data/post-responder.do', { method: 'post', //Use the Y.JSON utility to convert messages to a string data : Y.JSON.stringify(myMessages), //All response methods are encapsulated in //the on object on: {success: callback, failure: errorHandler } }) } )});
As you can see, the basic mode is the same in most lists. Apart from the support for ActiveX controls and JSONP examples, they are basically based on the same principle, but have different API changes at the top layer of core JavaScript interaction.
Note that in addition to the basic interactions listed here, all these libraries provide a large number of features. Although most of the Ajax work you can do can be processed through simple GET and POST requests, it is very useful to familiarize yourself with the advanced features in the selected library.