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.
The modern reintroduction of AJAX
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.
Fetch API
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
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
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
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);
Request - Simplified HTTP Client
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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools