本文转载自公众号“读芯术”(ID:AI_Discovery)
使用JavaScript时,总会有各种需要发出调用请求的情况,进行ajax调用什么技术更适合呢?
最初,尽管有一些方法可以在不刷新页面的情况下从服务器提取数据,但它们通常依赖于笨拙的技术。直到微软为Outlook电子邮件客户端的替代浏览器开发了XMLHttpRequest。它在2006年成为了Web标准。
2015年,Fetch API随ES6引入。通用的Request和Response接口提供了一致性,而Promises允许更容易的链接和没有回调的异步/等待。Fetch简洁,优雅且易于理解,但是还有其他不错的选择,本文将简要的含义、语法以及利弊。
以下代码展示了使用不同替代方法的基本HTTP GET和POST示例。现在开始吧~
XMLHttpRequest
XMLHttpRequest对象可用于从Web服务器请求数据。它是这次比较中最早的方法,尽管其他选择都优于它,但由于其向后兼容性和成熟度,它仍然有效且有用。
得到:
- var req= new XMLHttpRequest();//The onreadystatechange property
- //specifies a function to be
- //executed every time the status
- //of the XMLHttpRequest changes
- req.onreadystatechange = function() {
- if (this.readyState == 4 &&this.status == 200) {
- //The responseText property
- //returns a text string
- console.log(xhttp.responseText)
- //Do some stuff
- }
- };req.open("GET", "http://dataserver/users", true);
- req.send();
发送:
- varformData = new FormData();
- formData.append("name", "Murdock");
- var req = new XMLHttpRequest();
- req.open("POST", "http://dataserver/update");
- req.send(formData);
优点:
缺点:
Qwest
Qwest是一个基于Promise的简单ajax库,它支持XmlHttpRequest2的独立数据,例如ArrayBuffer,Blob和FormData。
得到:
- qwest.get('http://dataserver/data.json')
- .then(function(xhr, response) {
- // ...do some stuff whith data
- });
发送:
- qwest.post('http://dataserver/update',{
- firstname: 'Murdock',
- age: 30
- })
- .then(function(xhr, response) {
- // Make some useful actions
- })
- .catch(function(e, xhr, response) {
- // Process the error
- });
优点:
缺点:
JQuery.ajax
该库在不久前被广泛用于发出HTTP异步请求。jQuery的所有Ajax方法都返回XMLHTTPRequest对象的超集
得到:
- $.ajax({
- url: 'http://dataserver/data.json'
- }).done(function(data) {
- // ...do some stuff whith data
- }).fail(function() {
- // Handle error
- });
发送:
- $.ajax({
- type: "POST",
- url: 'http://dataserver/update',
- data: data,
- success: successCallBack,
- error: errorCallBack,
- dataType: dataType
- });
优点:
缺点:
Axios
[[323125]]
图源:unsplash
基于Promise的HTTP库,用于在浏览器和Nodejs上执行HTTP请求。
得到:
- axios({
- url: 'http://dataserver/data.json',
- method: 'get'
- })
发送:
- axios.post('http://dataserver/update',{
- name: 'Murdock'
- })
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
优点:
缺点:
SuperAgent
SuperAgent是ajax API,旨在提供灵活性,可读性和较低的学习曲线。它也可以与Node.js一起使用。
得到:
- request('GET','http://dataserver/data.json').then(
- success, failure);
.query()方法接受对象,这些对象与GET方法一起使用时将形成查询字符串。以下代码将产生路径/ dataserver / search?name = Manny&lastName = Peck&order = desc。
- request
- .get('/dataserver/search')
- .query({ name: 'Templeton' })
- .query({ lastname: 'Peck' })
- .query({ order: 'desc' })
- .then(res => {console.dir(res)}
- });
发送:
- request
- .post('http://dataserver/update')
- .send({ name: 'Murdock' })
- .set('Accept', 'application/json')
- .then(res => {
- console.log('result' +JSON.stringify(res.body));
- });
优点:
缺点:
[[323126]]
图源:unsplash
Http-client
Http-client允许使用JavaScript的访存API组成HTTP客户端。
得到:
- //usingES6 modules
- import { createFetch, base, accept, parse } from 'http-client'const fetch =createFetch(
- base('http://dataserver/data.json'),
- accept('application/json'),
- parse('json')
- )fetch('http://dataserver/data.json').then(response => {
- console.log(response.jsonData)
- })
发送:
- //usingES6 modules
- import { createFetch, method, params } from 'http-client'const fetch =createFetch(
- params({ name: 'Murdock' }),
- base('http://dataserver/update')
- )
优点:
缺点:
Fetch
Fetch是原生浏览器API,用于发出替代XMLHttpRequest的请求。与XMLHttpRequest相比,Fetch使网络请求更容易。Fetch API使用Promises避免XMLHttpRequest回调地狱。
得到:
- //WithES6 fetch
- fetch('http://dataserver/data.json')
- .then(data => {
- // ...do some stuff whith data
- }).catch(error => {
- // Handle error
- });
发送:
- fetch('http://dataserver/update',{
- method: 'post',
- headers: {
- 'Accept': 'application/json,text/plain, */*',
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({name: 'Murdock'})
- }).then(res=>res.json())
- .then(res => console.log(res));//ORwith ES2017 for example(async () => {
- const response = awaitfetch('http://dataserver/update', {
- method: 'POST',
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
- },
- body:JSON.stringify({name='Murdock'})
- });const result = awaitresponse.json();console.log(result);
- })();
优点:
缺点:
- {credentials: “same-origin.”}
[[323127]]
图源:unsplash
Fetch是一个新标准,新版本的Chrome和Firefox无需使用任何其他库就可支持它。
此外,Axios,SuperAgent或其他库都有适合的文档,易于使用,并且学习曲线不太高。在某些情况下,它们可以提供Fetch不具有的功能。
Fetch在JavaScript里是原生的,足以满足项目需求。如果没有特殊需求,我认为Fetch就是最合适的选择。
网页名称:Battle!用JavaScript发出HTTP请求的不同方法
链接地址:http://www.shufengxianlan.com/qtweb/news32/420732.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联