5 个顶级的 JavaScript Ajax 组件和库

在这篇文章中,我们将介绍一些用于AJAX调用的最好的JS库,包括jQuery,Axios和Fetch。欢迎查看代码示例!

AJAX是用来对服务器进行异步HTTP调用的一系列web开发技术客户端框架。 AJAX即Asynchronous JavaScript and XML(异步JavaScript和XML)。AJAX曾是web开发界的一个常见名称,许多流行的JavaScript小部件都是使用AJAX构建的。例如,有些特定的用户交互(如按下按钮)会异步调用到服务器,服务器会检索数据并将其返回给客户端——所有这些都不需要重新加载网页。

AJAX的现代化重新引入

JavaScript已经进化了,现在我们使用前端库和/或如React、Angular、Vue等框架构建了动态的网站。AJAX的概念也经历了重大变化,因为现代异步JavaScript调用涉及检索JSON而不是XML。有很多库允许你从客户端应用程序对服务器进行异步调用。有些进入到浏览器标准,有些则有很大的用户基础,因为它们不但灵活而且易于使用。有些支持promises,有些则使用回调。在本文中,我将介绍用于从服务器获取数据的前5个AJAX库。

Fetch API

Fetch API是XMLHttpRequest的现代替代品,用于从服务器检索资源。与XMLHttpRequest不同的是,它具有更强大的功能集和更有意义的命名。基于其语法和结构,Fetch不但灵活而且易于使用。但是,与其他AJAX HTTP库区别开来的是,它具有所有现代Web浏览器的支持。Fetch遵循请求-响应的方法,也就是说,Fetch提出请求并返回解析到Response对象的promise。

你可以传递Request对象来获取,或者,也可以仅传递要获取的资源的URL。下面的示例演示了使用Fetch创建简单的GET请求。

Python
fetch('https://www.example.com', { method: 'get' }) .then(response => response.json()) .then(jsonData => console.log(jsonData)) .catch(err => { //error block })
1
2
3
4
5
6
7
8
9
fetch ( 'https://www.example.com' , {
         method : 'get'
     } )
     . then ( response = > response . json ( ) )
     . then ( jsonData = > console . log ( jsonData ) )
     . catch ( err = > {
             / / error block
     } )
 

正如你所看到的,Fetch的then方法返回了一个响应对象,你可以使用一系列的then 进行进一步的操作。我使用.json() 方法将响应转换为JSON并将其输出到控制台。

假如你需要POST表单数据或使用Fetch创建AJAX文件上传,将会怎么样?此时,除了Fetch之外,你还需要一个输入表单,并使用FormData库来存储表单对象。

Python
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 })
1
2
3
4
5
6
7
8
9
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
} )
 

你可以在官方的Mozilla web文档中阅读更多关于Fetch API的信息。

Axios

Axios是一个基于XMLHttpRequest而构建的现代JavaScript库,用于进行AJAX调用。它允许你从浏览器和服务器发出HTTP请求。此外,它还支持ES6原生的Promise API。Axios的其他突出特点包括:

  • 拦截请求和响应。
  • 使用promise转换请求和响应数据。
  • 自动转换JSON数据。
  • 取消实时请求。

要使用Axios,你需要先安装它。

Python
npm install axios
1
2
npm install axios
 

下面是一个演示Axios行动的基本例子。

Python
// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
1
2
3
4
5
6
7
8
9
/ / Make a request for a user with a given ID
axios . get ( '/user?ID=12345' )
   . then ( function ( response ) {
     console . log ( response ) ;
   } )
   . catch ( function ( error ) {
     console . log ( error ) ;
   } ) ;
 

与Fetch相比,Axios的语法更简单。让我们做一些更复杂的事情,比如我们之前使用Fetch创建的AJAX文件上传器。

Python
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; });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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更具可读性。Axios也非常受React和Vue等现代库的欢迎。

jQuery

jQuery曾经是JavaScript中的一个前线库,用于处理从AJAX调用到操纵DOM内容的所有事情。虽然随着其他前端库的“冲击”,其相关性有所降低,但你仍然可以使用jQuery来进行异步调用。

如果你之前使用过jQuery,那么这可能是最简单的解决方案。但是,你将不得不导入整个jQuery库以使用$.ajax方法。虽然这个库有特定于域的方法,例如$.getJSON,$.get和$.post,但是其语法并不像其他的AJAX库那么简单。以下代码用于编写基本的GET请求。

Python
$.ajax({ url: '/users', type: "GET", dataType: "json", success: function (data) { console.log(data); } fail: function () { console.log("Encountered an error") } });
1
2
3
4
5
6
7
8
9
10
11
12
$ . ajax ( {
   url : '/users' ,
   type : "GET" ,
   dataType : "json" ,
   success : function ( data ) {
       console . log ( data ) ;
   }
   fail : function ( ) {
       console . log ( "Encountered an error" )
   }
} ) ;
 

jQuery好的地方在于,如果你有疑问,那么你可以找到大量的支持和文档。我发现了很多使用FormData()和jQuery进行AJAX文件上传的例子。下面是最简单的方法:

Python
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); } });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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是一个轻量级和渐进式的AJAX库,更侧重于可读性和灵活性。SuperAgent还拥有一个温和的学习曲线,不像其他库。它有一个针对Node.js API相同的模块。SuperAgent有一个接受GET、POST、PUT、DELETE和HEAD等方法的请求对象。然后你可以调用.then(),.end()或新的.await()方法来处理响应。例如,以下代码为使用SuperAgent的简单GET请求。

Python
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)); });
1
2
3
4
5
6
7
8
9
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 ) ) ;
   } ) ;
 

如果你想要做更多的事情,比如使用此AJAX库上传文件,那该怎么做呢? 同样超级easy。

Python
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);
1
2
3
4
5
6
7
8
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 ) ;
 

如果你有兴趣了解更多关于SuperAgent的信息,那么它们有一系列很不错的文档来帮助你开始这个旅程。

Request——简化的HTTP客户端

Request库是进行HTTP调用最简单的方法之一。结构和语法与在Node.js中处理请求的方式非常相似。目前,该项目在GitHub上有18K个星,值得一提的是,它是可用的最流行的HTTP库之一。 下面是一个例子:

Python
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. });
1
2
3
4
5
6
7
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 .
} ) ;
 

结论

从客户端进行HTTP调用在十年前可不是一件容易的事。前端开发人员不得不依赖于难以使用和实现的XMLHttpRequest。现代的库和HTTP客户端使得用户交互、动画、异步文件上传等前端功能变得更加简单。

我个人最喜欢的是Axios,因为我觉得它更易读更赏心悦目。你也可以忠于Fetch,因为它文档化良好且有标准化的解决方案。

你个人最喜欢的AJAX库是哪个? 欢迎各位分享你的看法。




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值