作者:Danny Markov
译者:前端小智
起源:tutorialzine
点赞再看,微信搜寻【大迁世界】关注这个没有大厂背景,但有着一股向上踊跃心态人。本文 GitHub
https://github.com/qq44924588... 上曾经收录,文章的已分类,也整顿了很多我的文档,和教程材料。**
最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。
github 地址:https://github.com/qq44924588...
在本教程中,咱们将学习如何应用 JS 进行AJAX调用。
1.AJAX
术语AJAX 示意 异步的 JavaScript 和 XML。
AJAX 在 JS 中用于收回异步网络申请来获取资源。当然,不像名称所暗示的那样,资源并不局限于XML,还用于获取JSON、HTML或纯文本等资源。
有多种办法能够收回网络申请并从服务器获取数据。 咱们将一一介绍。
2.XMLHttpRequest
XMLHttpRequest
对象(简称XHR)在较早的时候用于从服务器异步检索数据。
之所以应用XML,是因为它首先用于检索XML数据。当初,它也能够用来检索JSON, HTML或纯文本。
事例 2.1: GET
function success() { var data = JSON.parse(this.responseText) console.log(data)}function error (err) { console.log('Error Occurred:', err)}var xhr = new XMLHttpRequest()xhr.onload = successxhr.onerror = errorxhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")xhr.send()
咱们看到,要收回一个简略的GET申请,须要两个侦听器来解决申请的胜利和失败。咱们还须要调用open()
和send()
办法。来自服务器的响应存储在responseText
变量中,该变量应用JSON.parse()
转换为JavaScript 对象。
function success() { var data = JSON.parse(this.responseText); console.log(data);}function error(err) { console.log('Error Occurred :', err);}var xhr = new XMLHttpRequest();xhr.onload = success;xhr.onerror = error;xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");xhr.send(JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }));
咱们看到POST申请相似于GET申请。 咱们须要另外应用setRequestHeader
设置申请标头“Content-Type” ,并应用send办法中的JSON.stringify
将JSON注释作为字符串发送。
2.3 XMLHttpRequest vs Fetch
晚期的开发人员,曾经应用了好多年的 XMLHttpRequest
来申请数据了。 古代的fetch API
容许咱们收回相似于XMLHttpRequest(XHR)
的网络申请。 次要区别在于fetch()
API应用Promises,它使 API更简略,更简洁,防止了回调天堂。
3. Fetch API
Fetch 是一个用于进行AJAX调用的原生 JavaScript API,它失去了大多数浏览器的反对,当初失去了宽泛的利用。
3.1 API用法
fetch(url, options) .then(response => { // handle response data }) .catch(err => { // handle errors });
API参数
fetch()
API有两个参数
- url是必填参数,它是您要获取的资源的门路。
options
是一个可选参数。不须要提供这个参数来收回简略的GET申请。- method: GET | POST | PUT | DELETE | PATCH
headers: 申请头,如
{ “Content-type”: “application/json; charset=UTF-8” }
- mode: cors | no-cors | same-origin | navigate
- cache: default | reload | no-cache
- body: 个别用于POST申请
API返回Promise对象
fetch()
API返回一个promise对象。
- 如果存在网络谬误,则将回绝,这会在
.catch()
块中解决。 - 如果来自服务器的响应带有任何状态码(如
200
、404
、500
),则promise将被解析。响应对象能够在.then()
块中解决。
错误处理
请留神,对于胜利的响应,咱们冀望状态代码为200
(失常状态),然而即便响应带有谬误状态代码(例如404
(未找到资源)和500
(外部服务器谬误)),fetch()
API 的状态也是 resolved
,咱们须要在.then()
块中显式地解决那些。
咱们能够在response
对象中看到HTTP状态:
- HTTP状态码,例如200。
- ok –布尔值,如果HTTP状态代码为200-299,则为
true
。
3.3 示例:GET
const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .catch(err => console.error(err));getTodoItem.then(response => console.log(response));
Response { userId: 1, id: 1, title: "delectus aut autem", completed: false }
在下面的代码中须要留神两件事:
fetch
API返回一个promise对象,咱们能够将其调配给变量并稍后执行。- 咱们还必须调用
response.json()
将响应对象转换为JSON
错误处理
咱们来看看当HTTP GET
申请抛出500谬误时会产生什么:
fetch('http://httpstat.us/500') // this API throw 500 error .then(response => () => { console.log("Inside first then block"); return response.json(); }) .then(json => console.log("Inside second then block", json)) .catch(err => console.error("Inside catch block:", err));
Inside first then block➤ ⓧ Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
咱们看到,即便API抛出500谬误,它依然会首先进入then()
块,在该块中它无奈解析谬误JSON并抛出catch()
块捕捉的谬误。
这意味着如果咱们应用fetch()
API,则须要像这样显式地解决此类谬误:-
fetch('http://httpstat.us/500') .then(handleErrors) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error("Inside catch block:", err));function handleErrors(response) { if (!response.ok) { // throw error based on custom conditions on response throw Error(response.statusText); } return response;}
➤ Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
3.3 示例:POST
fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', body: JSON.stringify({ completed: true, title: 'new todo item', userId: 1 }), headers: { "Content-type": "application/json; charset=UTF-8" } }) .then(response => response.json()) .then(json => console.log(json)) .catch(err => console.log(err))
Response➤ {completed: true, title: "new todo item", userId: 1, id: 201}
在下面的代码中须要留神两件事:-
POST
申请相似于GET
申请。 咱们还须要在fetch()
API的第二个参数中发送method
,body
和headers
属性。- 咱们必须须要应用
JSON.stringify()
将对象转成字符串申请body
参数
4.Axios API
Axios API十分相似于fetch API,只是做了一些改良。我集体更喜爱应用Axios API而不是fetch()
API,起因如下:
- 为GET 申请提供
axios.get()
,为 POST 申请提供axios.post()
等提供不同的办法,这样使咱们的代码更简洁。 - 将响应代码(例如404、500)视为能够在
catch()
块中解决的谬误,因而咱们无需显式解决这些谬误。 - 它提供了与IE11等旧浏览器的向后兼容性
- 它将响应作为JSON对象返回,因而咱们无需进行任何解析
4.1 示例:GET
// 在chrome控制台中引入脚本的办法var script = document.createElement('script');script.type = 'text/javascript';script.src = 'https://unpkg.com/axios/dist/axios.min.js';document.head.appendChild(script);
axios.get('https://jsonplaceholder.typicode.com/todos/1') .then(response => console.log(response.data)) .catch(err => console.error(err));
Response{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
咱们能够看到,咱们间接应用response取得响应数据。数据没有任何解析对象,不像fetch()
API。
错误处理
axios.get('http://httpstat.us/500') .then(response => console.log(response.data)) .catch(err => console.error("Inside catch block:", err));
Inside catch block: Error: Network Error
咱们看到,500谬误也被catch()
块捕捉,不像fetch()
API,咱们必须显式解决它们。
4.2 示例:POST
axios.post('https://jsonplaceholder.typicode.com/todos', { completed: true, title: 'new todo item', userId: 1 }) .then(response => console.log(response.data)) .catch(err => console.log(err))
{completed: true, title: "new todo item", userId: 1, id: 201}
咱们看到POST办法十分简短,能够间接传递申请主体参数,这与fetch()API不同。
代码部署后可能存在的BUG没法实时晓得,预先为了解决这些BUG,花了大量的工夫进行log 调试,这边顺便给大家举荐一个好用的BUG监控工具 Fundebug。
原文:https://tutorialzine.com/2017...
交换
文章每周继续更新,能够微信搜寻【大迁世界 】第一工夫浏览,回复【福利】有多份前端视频等着你,本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,欢送Star。