Home > Article > Web Front-end > Share 5 top JavaScript Ajax component libraries
AJAX is a series of web development technology client frameworks used to make asynchronous HTTP calls to the server. This article shares 5 top JavaScript Ajax component libraries
AJAX is used to make asynchronous calls to the server. A series of web development technology client frameworks called by HTTP. AJAX stands for Asynchronous JavaScript and XML. AJAX was once a common name in the web development world, and many popular JavaScript widgets were built using AJAX. For example, certain user interactions (such as pressing a button) make asynchronous calls to the server, which retrieves the data and returns it to the client—all without reloading the web page.
JavaScript has evolved and now we build dynamic websites using front-end libraries and/or frameworks like React, Angular, Vue, etc. The concept of AJAX has also undergone significant changes, as modern asynchronous JavaScript calls involve retrieving JSON rather than XML. There are many libraries that allow you to make asynchronous calls to the server from a client application. Some are incorporated into browser standards, while others have a large user base because they are flexible and easy to use. Some support promises, others use callbacks. In this article, I will introduce the top 5 AJAX libraries for getting data from the server.
The Fetch API is a modern replacement for XMLHttpRequest for retrieving resources from the server. Unlike XMLHttpRequest, it has a more powerful feature set and more meaningful naming. Based on its syntax and structure, Fetch is both flexible and easy to use. However, what sets it apart from other AJAX HTTP libraries is that it has support for all modern web browsers. Fetch follows a request-response approach, that is, Fetch makes a request and returns a promise that resolves to a Response object.
You can pass the Request object to get it, or you can just pass the URL of the resource you want to get. The following example demonstrates using Fetch to create a simple GET request.
fetch('https://www.example.com', { method: 'get' }) .then(response => response.json()) .then(jsonData => console.log(jsonData)) .catch(err => { //error block })
As you can see, Fetch's then method returns a response object, and you can use a series of then for further operations. I use the .json() method to convert the response to JSON and output it to the console.
What if you need to POST form data or use Fetch to create an AJAX file upload? At this point, in addition to Fetch, you also need an input form and use the FormData library to store the form object.
var input = document.querySelector('input[type="file"]')var data = new FormData() data.append('file', input.files[0]) data.append('user', 'blizzerand') fetch('/avatars', { method: 'POST', body: data })
Axios is a modern JavaScript library built on XMLHttpRequest for making AJAX calls. It allows you to make HTTP requests from browsers and servers. In addition, it also supports ES6 native Promise API. Other outstanding features of Axios include:
1. Interception of requests and responses.
2. Use promise to convert request and response data.
3. Automatically convert JSON data.
4. Cancel the real-time request.
5. To use Axios, you need to install it first.
npm install axios
The following is a basic example demonstrating Axios in action.
// Make a request for a user with a given IDaxios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Compared with Fetch, Axios has a simpler syntax. Let's do something more complex, like the AJAX file uploader we created earlier using Fetch.
var data = new FormData(); data.append('foo', 'bar'); data.append('file', document.getElementById('file').files[0]); var config = { onUploadProgress: function(progressEvent) { var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); } }; axios.put('/upload/server', data, config) .then(function (res) { output.className = 'container'; output.innerHTML = res.data; }) .catch(function (err) { output.className = 'container text-danger'; output.innerHTML = err.message; });
Axios is more readable. Axios is also very popular with modern libraries like React and Vue.
jQuery used to be a front-line library in JavaScript, used to handle everything from AJAX calls to manipulating DOM content. Although its relevance has decreased with the "impact" of other front-end libraries, you can still use jQuery to make asynchronous calls.
If you have used jQuery before, this is probably the easiest solution. However, you will have to import the entire jQuery library to use the $.ajax method. Although this library has domain-specific methods such as $.getJSON, $.get and $.post, its syntax is not as simple as other AJAX libraries. The following code is used to write a basic GET request.
$.ajax({ url: '/users', type: "GET", dataType: "json", success: function (data) { console.log(data); } fail: function () { console.log("Encountered an error") } });
The good thing about jQuery is that if you have questions, then you can find a lot of support and documentation. I found many examples of AJAX file upload using FormData() and jQuery. Here is the simplest way:
var formData = new FormData(); formData.append('file', $('#file')[0].files[0]); $.ajax({ url : 'upload.php', type : 'POST', data : formData, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success : function(data) { console.log(data); alert(data); } });
SuperAgent is a lightweight and progressive AJAX library that focuses more on readability and flexibility. SuperAgent also has a gentle learning curve, unlike other libraries. It has a module for the same Node.js API. SuperAgent has a request object that accepts methods such as GET, POST, PUT, DELETE, and HEAD. You can then call .then(), .end() or the new .await() method to handle the response. For example, the following code is a simple GET request using SuperAgent.
request .post('/api/pet') .send({ name: 'Manny', species: 'cat' }) .set('X-API-Key', 'foobar') .set('Accept', 'application/json') .then(function(res) { alert('yay got ' + JSON.stringify(res.body)); });
What if you want to do more, like upload files using this AJAX library? Also super easy.
request .post('/upload') .field('user[name]', 'Tobi') .field('user[email]', 'tobi@learnboost.com') .field('friends[]', ['loki', 'jane']) .attach('image', 'path/to/tobi.png') .then(callback);
The Request library is one of the easiest ways to make HTTP calls. The structure and syntax are very similar to how requests are handled in Node.js. Currently, the project has 18K stars on GitHub, and it's worth mentioning that it's one of the most popular HTTP libraries available. Here is an example:
var request = require('request'); request('http://www.google.com', function (error, response, body) { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. });
My personal favorite is Axios because it is easier to read and more pleasing to the eye. You can also stay loyal to Fetch because it is well documented and has standardized solutions.
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!
The above is the detailed content of Share 5 top JavaScript Ajax component libraries. For more information, please follow other related articles on the PHP Chinese website!