Introduction to Ajax
Ajax is all called "Asynchronous JavaScript and xml", meaning "asynchronous JavaScript and XML". With Ajax we can send requests to the server to interact with the data without blocking the page, or to interpret the asynchronous data transfer. With the help of Ajax, our web page can update the display of data only by local refresh, reduce the amount of unnecessary data, greatly improve the user experience, shorten the waiting time for the user, make the Web application smaller, faster and more friendly.
Of course, the above is a commonplace content, as a qualified developer basic are familiar with it, here only for those who have just started to do a simple introduction. For more information about Ajax, please visit W3school:http://www.w3school.com.cn/php/php_ajax_intro.asp
Native Ajax
Basically all modern browsers support native AJAX functionality, and here's a detailed introduction to how we can initiate and process Ajax requests using native JS.
1. Get the XMLHttpRequest object
var xhr = new XMLHttpRequest (); Get the browser's built-in XMLHttpRequest object
If your project application does not consider the low version of IE, then you can directly use the method above, all modern browsers (Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects. If you need to be compatible with older versions of IE (IE5, IE6), you can use ActiveX objects:
var xhr;if (window. XMLHttpRequest) { xhr=new XMLHttpRequest ();} else if (window. ActiveXObject) { //compatible with old version browser xhr=new activexobject ("Microsoft.XMLHTTP");}
2. Parameter Configuration
With the XMLHttpRequest object, we also need to configure some of the requested parameter information to complete the data interaction, using the Open method:
var xhr;if (window. XMLHttpRequest) { xhr=new XMLHttpRequest ();} else if (window. ActiveXObject) { xhr=new ActiveXObject ("Microsoft.XMLHTTP");} if (XHR) { xhr.open (' Get ', '/test/', true);//Send an asynchronous request to the '/test/' path in the way of a GET request}
The Open method creates a new HTTP request for us, where the first parameter is the request mode, usually ' GET ' or ' POST ', the second parameter is the request URL, the third parameter is async, and the default is true.
3. Sending the request
After the basic parameter information is configured, we call the Send method directly, and the code is as follows:
var xhr;if (window. XMLHttpRequest) { xhr=new XMLHttpRequest ();} else if (window. ActiveXObject) { xhr=new ActiveXObject ("Microsoft.XMLHTTP");} if (XHR) { xhr.open (' GET ', '/test/', true); Xhr.send (); Call the Send method for sending the request}
It is important to note that if you use the Get method to pass parameters, we can directly put the parameters behind the URL, such as '/test/?name=luozh&size=12 ', if we use the Post method, then our parameters need to be written in the Send method, such as:
Xhr.open (' POST ', '/test/', true); Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Set the request header to form to submit xhr.send (' name=luozh&size=12 ');
It will eventually be passed as form data:
If the request header is not set, native Ajax defaults to sending the data using the Content-type is ' text/plain;charset=utf-8 ', and if it is written in the form above, we will eventually transmit it in such a way:
Obviously this is not the data format the server expects, so we can write:
Xhr.open (' POST ', '/test/', true); Xhr.send (Json.stringify ({name: ' Luozh ', size:12}));
The final transfer format is as follows:
So we can pass the JSON string directly to the background processing, of course, the background may be configured accordingly.
4. Monitoring Status
After the AJAX request is sent, we need to monitor and handle the status returned by the server, here we need to use the onReadyStateChange method, the code is as follows:
var xhr;if (window. XMLHttpRequest) { xhr=new XMLHttpRequest ();} else if (window. ActiveXObject) { xhr=new ActiveXObject ("Microsoft.XMLHTTP");} if (XHR) { xhr.open (' GET ', '/test/', true); Sends an asynchronous request to the '/test/' path as a GET request xhr.send (); Xhr.onreadystatechange = function () { //use onreadystatechange to monitor status if (xhr.readystate = = = 4) { // A readystate of 4 indicates that the request response is complete if (xhr.status = = =) { //status = 200 indicates the request succeeded Console.log (' execution succeeded '); } else { C14/>console.log (' execution error ');}}}}
Above we use onreadystatechange to monitor the state, and internally use readystate to get the current state. ReadyState altogether has 5 stages, and when it is 4 it indicates that the response content resolution is complete and can be called at the client. When readystate is 4 o'clock, we also get the status code by status, the code is 200 when the success is executed, otherwise the error code is executed.
Of course we can use onload instead of onreadystatechange equals 4, because OnLoad is called only when the state is 4, and the code is as follows:
Xhr.onload = function () { //call onload if (xhr.status = = =) { //status = 200 indicates success of request Console.log (' execution succeeded ') ; } else { console.log (' execution error '); } }
However, it is important to note that IE's support for the OnLoad property is not friendly.
In addition to the onload, there are:
- Onloadstart
- OnProgress
- Onabort
- OnTimeOut
- OnError
- Onloadend
and other events, interested students can personally to practice their usefulness.
These are common code for native AJAX request data.
Ajax in other library frameworksAjax in 1.jQuery
As one of the most widely used libraries, jquery has a good package of native Ajax code that has been greatly improved in terms of compatibility and ease of use, making Ajax calls very simple. Here's a simple jquery ajax code:
$.ajax ({ method: ' GET ',//1.9.0 This version with ' type ' URL: "/test/", dataType: ' JSON '}). Done (function () { Console.log (' execution succeeded ');}). Fail (function () { console.log (' execution error ');})
Unlike native Ajax, the default Content-type in jquery is ' application/x-www-form-urlencoded; Charset=utf-8 ', to learn more about jquery Ajax information can be in the official document:http://api.jquery.com/jquery.ajax/
Ajax in the 2.vue.js
Vue.js as the current hot front-end framework, in fact, it does not include AJAX functionality, but through the form of plug-ins additional needs to be referenced in the project, its official recommendation Ajax plug-in is Vue-resource, the following is the Vue-resource request code:
Vue.http.get ('/test/'). Then ((response) = { Console.log (' execution succeeded ');}, (response) = { Console.log (' Execution error ');});
Vue-resource supports the Promise API while supporting the current Firefox, Chrome, Safari, Opera and ie9+ browsers that are incompatible with browser compatibility IE8, after all, the Vue itself is not compatible with IE8. For more information about Vue-resource, you can take a look at the GitHub documentation:Https://github.com/vuejs/vue-resource
Ajax in the 3.angular.js
Ajax in Angular.js here mainly refers to the 1.x version of angular, because ANGULAR2 is not currently recommended for use in production environments.
var myApp = angular.module (' MyApp ', []), var Myctrl = Myapp.controller (' Myctrl ', [' $scope ', ' $http ', function ($scope, $ HTTP) { $http ({ method: ' GET ', URL: '/test/', headers: {' content-type ': ' application/ x-www-form-urlencoded; Charset=utf-8 '} }). Success (function (data) { Console.log (' execution succeeded '); }). Error (function () { console.log (' execution error '); });}]);
In angular, we need to register a $http event on the controller before we can perform Ajax internally. Angular's Ajax default content-type is ' Application/json;charset=utf-8 ', so you'll need to set the Headers property if you want to submit it as a form. For more information on Angular Ajax, you can get to the official document:https://docs.angularjs.org/api/ng/service/$http(may need to FQ)
Ajax in 4.React
In react I prefer to use fetch to request data, of course, it is not only applicable to react, in any kind of framework such as the above Vue, angular can be used, because it has been supported by the current mainstream browser, as to its main functions and usage, I will explain below.
Fetch API
Fetch API is based on Promise design, due to Promise browser compatibility issues and the Fetch API itself compatibility issues, some browsers temporarily do not support the Fetch API, browser compatibility diagram is as follows:
Of course, we can use some plug-ins to solve compatibility problems, such as: Fetch-polyfill, Es6-promise, FETCH-IE8 and so on.
With fetch we can write Ajax requests very easily, and we compare them with native Xmlhttprequst objects and fetch:
Xmlhttprequst API
Xmlhttprequst Apivar xhr = new XMLHttpRequest (), Xhr.open (' GET ', '/test/', true); xhr.onload = function () { console. Log (' execution succeeded ');}; Xhr.onerror = function () { console.log (' execution error ');}; Xhr.send ();
Fetch API
Fetch ('/test/'). Then (function (response) { return Response.json ();}). Then (function (data) { Console.log (' execute success ');}). catch (function (e) { console.log (' execution error ');});
It can be seen that after using fetch our code is more concise and semantically, and the way of chaining calls makes it smoother and clearer. With the continuous improvement of the browser kernel, future XMLHttpRequest will be replaced by fetch gradually. A detailed introduction to fetch can be:1190000003810652
cross-Domain ajax
Introducing a variety of Ajax APIs, one of the key issues that we can't avoid is cross-domain, which focuses on how Ajax is handled across domains.
There are 4 main ways to handle Ajax cross-domain issues:
Using IFRAME
Using JSONP
Using proxies
Using the XMLHttpRequest Level2 provided by HTML5
1th and 2nd way everyone should be very familiar with, all belong to the front-end of the live, here do not introduce, here is mainly about 3rd and 4th ways.
This can be understood by means of proxies:
By creating a proxy on the Web server side of the same domain name:
Beijing server (domain name: www.beijing.com)
Shanghai Server (domain name: www.shanghai.com)
For example, in Beijing's Web server Backstage (www.beijing.com/proxy-shanghaiservice.php) to call the Shanghai Server (www.shanghai.com/services.php) service, And then return the access results to the front end, so that the front-end calls to Beijing with the domain name service and call Shanghai service effect is the same.
The use of XMLHttpRequest Level2 requires the background to configure the request header accordingly:
PHP syntax
Header (' access-control-allow-origin: * ');
Header (' Access-control-allow-methods:get,post ');
The * above can be replaced by the domain name that is allowed to access, * indicates that all domain names can be accessed.
Thus, the 3rd and 4th way is mainly the background of the work, the front-end only need to call it.
Summary
No matter how changeable the syntax of Ajax, regardless of how libraries and frameworks encapsulate Ajax, it's just a tool for implementing asynchronous data interactions, we just need to understand the Ajax implementation principles of native JS and understand the concepts and processes of XMLHttpRequest and promise. can easily be used in the era of asynchronous data interaction.
An analysis of Ajax grammar