On the _javascript skills of Ajax grammar

Source: Internet
Author: User
Tags error code

Ajax is a very common technology at present, and it is a technology worthy of discussion and research. This article will share with you the new and old syntax of Ajax with respect to the development of Ajax and the way in which they are used in different library frameworks.

Introduction to Ajax

Ajax is all called "Asynchronous JavaScript and xml", meaning "asynchronous JavaScript and XML". We can send it to the server via Ajax, and it can be understood as asynchronous data transfer without blocking the page. With the help of Ajax, our web pages need only local refresh to update the display of data, reduce the amount of unnecessary data, greatly improve the user experience, shorten the time users wait, making Web applications smaller, faster and friendlier.

Of course, all the above is commonplace content, as a qualified developers are basically familiar with, here only for those who just beginners do a simple introduction. For more information on Ajax, please w3school to understand: 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 description of how we can initiate and process Ajax requests using native JS.

1. Get XMLHttpRequest Object

var xhr = new XMLHttpRequest(); // 获取浏览器内置的XMLHttpRequest对象

If your project application does not consider the low version of IE, you can use the above method directly, all modern browsers (Firefox, Chrome, Safari and Opera) have built a XMLHttpRequest object. 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 the 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 to:

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 form of a GET request
}

The Open method creates a new HTTP request for us, where the first parameter is the request method, typically ' get ' or ' POST ', the second parameter is the request URL, the third argument is asynchronous, and the default is true.

3. Send Request

Having configured the basic parameter information, we call the Send method directly to send the request with the following code:

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
}

The note here is that if you use the Get method to pass parameters, we can put the parameters directly behind the URL, such as '/test/?name=luozh&size=12 '; If you 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 the form form submit
xhr.send (' name=luozh&size=12 ');

Will eventually be passed as form data:

If you do not set the request header, native Ajax will default to send the data using the Content-type is ' text/plain;charset=utf-8 ', if you follow the parameters written above, the form of our final transmission is as follows:

Obviously this is not the data format that the server expects, and we can write this:

Xhr.open (' POST ', '/test/', true);
Xhr.send (json.stringify ({name: ' Luozh ', size:12}));

The final transport 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 sending the AJAX request, we need to monitor the status of the server return and handle it accordingly, 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 Xhr.send () to the '/test/' path in the form of a GET request
  ;
  Xhr.onreadystatechange = function () {/  /using onreadystatechange monitoring status
    if (xhr.readystate = = 4) {  // A readystate of 4 indicates that the request response completion
      if (Xhr.status = =) {  //status is 200 indicates a successful
        console.log (' execution succeeded ');
      } else { C21/>console.log (' execute error ');}}}

Above we use onreadystatechange to monitor the state and use readystate internally to get the current state. ReadyState has a total of 5 stages, when it is 4, the response content resolution completed, can be called on the client. When the readystate is 4 o'clock, we get the status code, which executes the success code when the status code is 200, or executes the error code.

Of course we can use the onload instead of onreadystatechange equals 4, because the onload is only called when the state is 4, the code is as follows:

Xhr.onload = function () {  //call onload
  if (xhr.status = =) {  //Status 200 indicates successful
    Console.log (' execution successful ') ;
  } else {
    Console.log (' Error executing ');
  }  

However, it should be noted that IE's support for the onload attribute is not friendly.
Besides 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 frameworks

Ajax in the 1.jQuery

As one of the most heavily populated libraries, jquery encapsulates native Ajax code in a very good way, improving compatibility and ease of use, making Ajax calls very simple. Here's a simple jquery ajax code:

$.ajax ({method
  : ' Get ',//1.9.0 the ' type ' URL before this version
  : "/test/",
  dataType: ' JSON '
})
. Done (function () {
  Console.log (' successful execution ');
}
Fail (function () {
  console.log (' Error executing ');
})

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 added to the official document: http://api.jquery.com/jquery.ajax/

Ajax in the 2.vue.js

Vue.js as the current popular front-end framework, in fact, it does not contain AJAX functionality, but the form of plug-ins in addition to the need to refer to the project, its official recommendation Ajax Plug-ins for 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 current Firefox, Chrome, Safari, Opera, and ie9+ browsers that are incompatible with browser compatibility IE8, after all, Vue is not compatible with IE8 itself. For more information about Vue-resource you can go to the GitHub document: Https://github.com/vuejs/vue-resource

Ajax in the 3.angular.js

Ajax in Angular.js mainly refers to the 1.x version of angular, because ANGULAR2 is not currently recommended for use in a production environment.

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 (' Error executing ');
  }
];

In angular, we need to register a $http event on the controller before Ajax can be executed internally. Angular's Ajax default content-type is ' Application/json;charset=utf-8 ', so if you want to submit it in a form, you need to set the headers attribute. For more information on angular Ajax you can go to the official document: https://docs.angularjs.org/api/ng/service/$http (may need FQ)

Ajax in the 4.React

In react I prefer to use fetch to request data, of course it is not only applicable to react, in any framework such as the above Vue, angular can be used, because it has been supported by the current mainstream browsers, as for its main features and usage, I will explain below.

Fetch API

The fetch API is based on the 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 the compatibility problem, such as: Fetch-polyfill, Es6-promise, FETCH-IE8 and so on.

Using fetch we can easily write Ajax requests, we use the native Xmlhttprequst objects and fetch to compare:

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 (' Error executing ');
Xhr.send ();

Fetch API

Fetch ('/test/'). Then (function (response) {return
  Response.json ();
}). Then (function (data) {
  console.log (' successful execution ');
}). catch (function (e) {
  console.log (' Error executing ');
});

We can see that our code is simpler and more semantically used after the fetch, and the way the chain calls it is more fluid and clearer. With the continuous improvement of the browser kernel, the future xmlhttprequest will gradually be replaced by the fetch. Detailed introduction of the fetch can be: https://segmentfault.com/a/1190000003810652

Cross-Domain Ajax

Introduced a variety of Ajax APIs, we can not avoid an important problem is cross-domain, here focus on the Ajax Cross-domain processing mode.

There are 4 main ways to handle Ajax Cross-domain problems:

    1. Using IFRAME
    2. Using JSONP
    3. Use of agents
    4. 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 is not to do the introduction, here mainly introduces the 3rd and 4th ways.

This can be understood by means of an agent:

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 the background of the Web server in Beijing (www.beijing.com/proxy-shanghaiservice.php) to invoke the service of Shanghai Server (www.shanghai.com/services.php), Then return the results to the front end, so that the front-end call 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 headers accordingly:

PHP Syntax
header (' access-control-allow-origin: * ');
Header (' Access-control-allow-methods:get,post ');

The above * number can be replaced by the allowed access to the domain name, * means that all domain names can be accessed.

This shows that the 3rd and 4th way is mainly in the background of the work, the front-end only need to call on it.

Summarize

No matter how changeable the syntax of Ajax is, no matter how libraries and frameworks encapsulate Ajax, it's just a tool for asynchronous data interaction, and we just need to understand the principles of Ajax in native JS, understand the concepts and processes of XMLHttpRequest and promise, It's easy to be able to do it in an era of asynchronous data interaction.

The above is the entire content of this article, I hope to help you, but also hope that a lot of support cloud Habitat community!

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.