An analysis of Ajax grammar

Source: Internet
Author: User

Ajax is a very common technology, it is also worth exploring and studying a technology. This article will focus on the development process of Ajax and its use in different library frameworks to share with you the new and old Grammar of Ajax. An analysis of Ajax grammar
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, interact with the data without blocking the page, or interpret it as 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 to send 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"); To set the request header as a form submission
Xhr.send (' name=luozh&size=12 ');

It will eventually be passed as form data:

An analysis of Ajax grammar

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:

An analysis of Ajax grammar

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:

An analysis of Ajax grammar

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); Send an asynchronous request to the '/test/' path in the way of a GET request
Xhr.send ();
Xhr.onreadystatechange = function () {//use onreadystatechange to monitor status
if (xhr.readystate = = = 4) {//ReadyState = 4 indicates request response complete
if (xhr.status = = =) {//status = 200 indicates successful request
Console.log (' successful execution ');
} else {
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 successful request
Console.log (' successful execution ');
} else {
Console.log (' execution error ');
}
}

However, it is important to note that IE's support for the OnLoad property is not friendly.

Besides OnLoad, there's

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 frameworks
Ajax 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 before using ' type '
URL: "/test/",
DataType: ' JSON '
})
. Done (function () {
Console.log (' successful execution ');
})
. 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 (' successful execution ');
}, (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 (' successful execution ');
}). 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:

An analysis of Ajax grammar

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 API
var xhr = new XMLHttpRequest ();
Xhr.open (' GET ', '/test/', true);

Xhr.onload = function () {
Console.log (' successful execution ');
};

Xhr.onerror = function () {
Console.log (' execution error ');
};

Xhr.send ();

Fetch API

Fetch ('/test/'). Then (function (response) {
return Response.json ();
}). Then (function (data) {
Console.log (' successful execution ');
}). 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: www1.qixoo.com)
Shanghai Server (domain name: www2.qixoo.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.
Summarize

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

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.